Sorry Led for the interruption but I just want to ask Keith a question about ajax.
Hi Keith, can you explain to me about these code above. As my knowledge, the basic ajax, in the server side, it only processes data and return a variable like : echo $response. But in the code, we have:
So which one is the $response in that case? How do we know which one is $response?
And also, for the server-side( in this example, : utilizadores/create), in the UtilizadoreController, we should return it as: echo $response or send to a view?
What I mean by is what we have to do in the server-side when we receive the request of an ajax function. It would be great if there is a sample code of ajax in both side in Yii. Thank a lot
The options that are being used are documented here.
The documentation for the success callback (from the jQuery site) states:
So the response from the server is held in the first parameter, which is named data in your case. This might contain HTML, JSON or something else depending on what your action outputs. You should use the dataType attribute to specify the format of the data that your action provides.
In your action, if you want to output JSON for ajax requests, you can do something like this:
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode($results);
Yii::app()->end();
}
Well, but in the Controller, the output is :$this->render (array…) not echo $data or something. And do I have to create a new Controller to handle ajax function? For example I have controller and view for url: site/index, if I use ajax in this view, I should send it to another controller/view or could send it back to site/index? When the ajax send request to site/index controller, the variables will be 2:
In the controller:
if (isset($_POST['ajaxrequest']))
{
// do default stuff;
// add more thing for ajaxrequest;
$this->render('site/index',array('stuff'=>$stuff, 'ajaxResponse'=>$ajaxResponse;)
}else
{
// do default stuff;
$this->render('site/index',array('stuff'=>$stuff));
}
In the view:
// render default view from $stuff
<javascript>ajax code here</javascript>
<div = 'display>
// display $ajaxresponse here when the ajax function run successfully.
</div>
Don’t use the render method if you’re outputting JSON; render will generate an HTML page. If you want to output JSON, use echo CJSON::encode($yourData);
Regarding how to handle the Ajax requests, that’s very much a personal decision and will depend on how you’ve structured your application. Regardless of whether you split ajax and non-ajax functionality into different controllers, I would suggest having each action dedicated to either rendering a page or echoing JSON data; don’t do both things in the same action.
If your javascript callback is expecting HTML, then you can use render (or renderPartial).