$(document).ready(function() { $("#a...">

How to send jQuery ajax response from CakePhp?

I have this script in a view:

<script type="text/javascript"> $(document).ready(function() { $("#addbrand").click(function() { $.ajax({ url : '../brands/add', data : { name : "test", shortname : "tst" }, dataType : 'json', success : function(html, textStatus) { alert('Success ' + textStatus + html); }, error : function(xhr, textStatus, errorThrown) { alert('An error occurred! ' + errorThrown); } }); }); });</script> 

And in the add controller, I have the following lines:

 ... else if($this->request->is('ajax')){ if ($this->Brand->save($this->request->query)) { // How to send feedback!? }else{ // How to send feedback!? } $this->autoRender = false; exit(); } 

When I click addbrand, the Ajax operation is successful, and I can see the added row in the database, but I do not know how to send an error message or a successful message to the user. I read a few tutorials, but none of them was dedicated to cakephp2.0, while everything was changed in 2.x. I also read JSON and XML views , but unfortunately I didn't understand anything !!! I need to send a status code. If the status was ok, I should send an array of strings (actually to the brand names), and if the status is not ok, I should send a string that explains why the operation was not successful. I would be very grateful if anyone could help me. Thanks


Update:

I changed the code. I used CakeResponse (), and now my action looks like this:

 if($this->RequestHandler->isAjax()){ if ($this->Brand->save($this->request->query)) { return new CakeResponse(array('body'=> json_encode(array('val'=>'test ok')),'status'=>200)); }else{ return new CakeResponse(array('body'=> json_encode(array('val'=>'test not ok')),'status'=>500)); } } 

Using CakeResponse I can handle possible responses in jQuery.

 $("#addbrand").click(function() { $.ajax({ url : '../brands/add', data : { name : "test", shortname : "tst" }, dataType : 'json', success : function(data) { alert("The brand has been saved"); }, error : function(data) { alert("Eorror occured"); }, complete : function(data) { alert($.parseJSON(data.responseText).val); } }); }); 

Although it seems to me that everything is working now, and I can send several variables via Ajax between the client and server in JSON format, I need to know if this is the standard way to send Ajax responses to CakePHP or not? Is there any other easier way to do this?

+4
source share
2 answers

The following lines of code do exactly what return new CakeResponse(array('body'=> json_encode(array('val'=>'test ok')),'status'=>200)); does in my question:

 $this->set('val','test ok'); $this->set('_serialize',array('val')); $this->response->statusCode(200); 

Remember that you need to do two important things:

  • Add Router::parseExtensions('json'); in App / Config / routs.php.
  • Add var $components = array("RequestHandler"); to the controller.

I think this is better because you do not need to return anything. In the previous solution, we had to return the cakeresponse object, and this is not easy with the nature of the action.

+7
source

You should use JSON views with route extensions : First, you need to configure route extensions. This is usually done with:

 Router::parseExtensions('json'); // In App/Config/routes.php 

This will allow the router to handle the "json" extension and know how to process the request, for example: www.example.com/people/index.json

 if($this->RequestHandler->isAjax()){ if ($this->Brand->save($this->request->query)) { //Logic for success } else { //Logic for save failure } } 

At this point, you have the option to choose between viewing data using a serialization key or using viewing data with view files (copied from CakeBook):

 <?php // Controller code class PostsController extends AppController { public function index() { $this->set(compact('posts', 'comments')); } } // View code - app/View/Posts/json/index.ctp foreach ($posts as &$post) { unset($post['Post']['generated_html']); } echo json_encode(compact('posts', 'comments')); 

Please note that the view is under ... / Views / Posts / json / ... You can have several extensions in the router so that you can return and process all kinds of content - after all, this is just a data view.

Hooray!

+1
source

Source: https://habr.com/ru/post/1434591/


All Articles