Getting json response on Ajax response callback

I am trying to create a small ajax chat system (just for this) and I am using prototype.js to handle the ajax part.

One thing I read in the help is that if you return the json data, the callback function will populate that json data in the second parameter.

So, in my php file that is being called, I have:

header('Content-type: application/json'); if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true) echo json_encode(array('lastid' => $acs_ajch_sql->msgid)); else echo json_encode(array('error' => $response)); 

In an ajax request, I have:

 onSuccess: function (response,json) { alert(response.responseText); alert(json); } 

The warning response.responseText gives me {"lastid": 8}, but json gives me null.

Does anyone know how I can make this work?

+7
javascript prototypejs ajax php
source share
4 answers

This is the correct syntax for getting prototype JSON

 onSuccess: function(response){ var json = response.responseText.evalJSON(); } 
+22
source share

There is a Response: Response.responseJSON property that is populated with JSON objects only if the backend returns Content-Type: application / json, that is, if you do something like this in your internal code:

 $this->output->set_content_type('application/json'); $this->output->set_output(json_encode($answer)); //this is within a Codeigniter controller 

in this case Response.responseJSON! = undefined, which you can check on the receiving side in the onSuccess (t) handler:

 onSuccess:function(t) { if (t.responseJSON != undefined) { // backend sent some JSON content (maybe with error messages?) } else { // backend sent some text/html, let say content for my target DIV } } 

I do not answer the question about the second parameter of the handler, but if it exists, then, for sure, Prototype will provide it only in the case of the correct type of response content.

+3
source share

This comes from the official representative of the prototype:

Evaluating a JavaScript response Sometimes an application is designed to send JavaScript code as an answer. If the content type of the response matches the JavaScript MIME type, then this is true, and Prototype automatically eval () the returned code. You do not need to handle the response explicitly unless you need it.

Alternatively, if the response contains X-JSON, its contents will be parsed, saved as an object, and callbacks sent as the second argument:

new Ajax.Request ('/ some_url', {method: 'get', onSuccess: function (transport, json) {

  alert(json ? Object.inspect(json) : "no JSON object"); } 

});

Use this function if you want to get non-trivial data with Ajax, but want to avoid the overhead of parsing XML responses. JSON is much faster (and easier) than XML.

+2
source share

You can also just skip the framework. Here's a cross browser compatible way to make ajax used in comment widgets:

 // fetches comments from the server
 CommentWidget.prototype.getComments = function () {
   var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id; 
   this.asyncRequest ('GET', commentURL, null);
 }


 // initiates an XHR request
 CommentWidget.prototype.asyncRequest = function (method, uri, form) {
   var o = createXhrObject ()
   if (! o) {return null;  } 
   o.open (method, uri, true);
   o.setRequestHeader ('X-Requested-With', 'XMLHttpRequest');
   var self = this;
   o.onreadystatechange = function () {self.callback (o)};
   if (form) { 
     o.setRequestHeader ('Content-Type', 'application / x-www-form-urlencoded; charset = UTF-8');
     o.send (makePostData (form)); 
   } else {
     o.send (''); 
   }  
 }

 // after a comment is posted, this rewrites the comments on the page
 CommentWidget.prototype.callback = function (o) {                  
   if (o.readyState! = 4) {return}
   // turns the JSON string into a JavaScript object.
   var response_obj = eval ('(' + o.responseText + ')');
   this.comments = response_obj.comments;
   this.refresh ()
 }

I open this code here http://www.trailbehind.com/comment_widget

+1
source share

All Articles