views:

1131

answers:

2

Hey!

I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part.

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

So in my php file that gets 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));

On the ajax request I have:

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

The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null.

Anyone know how I can make this work?

+7  A: 

This is the correct syntax for retrieving JSON with Prototype

onSuccess: function(response){
   var json = response.responseText.evalJSON();
}
Jose Basilio
Thanks! But I did read somewhere about that second parameter thing :P
AntonioCS
Thanks Jose. Yeah, http://www.prototypejs.org/learn/introduction-to-ajax it says that second param is json, crap, wont work for me - onSuccess: function(transport, json){ alert(json ? Object.inspect(json) : "no JSON object"); }
umpirsky
+1  A: 

You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget:

//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-sourced this code here http://www.trailbehind.com/comment_widget

Andrew Johnson
Cool. Thanks for this.I just used prototype because I do some more stuff with it, like using delay, update and some other small things.
AntonioCS