Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send JSON with AJAX

Is there anything special I have to do to a JSON object before I send it with AJAX? My code looks like this:

runAjax(JSON.stringify(data));

}

function runAjax(JSONstring)
{
    ajax = getHTTPObject();
    var params = "?data=" + JSONstring;
    ajax.open("POST", "createtrip.php", true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("Content-length", params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = serverSpeaks;
    ajax.send(params);
}

Right now the server is not receiving the data. I get null on the server side but the client side JSONString is set. Is there something I'm doing wrong?

like image 877
Dan Avatar asked Aug 27 '09 17:08

Dan


1 Answers

You are sending data over POST, you don't need the '?' character at the beginning of the params variable, also I recommend you to encode the JSONString to avoid problems.

Note that you are missing the var statement for the ajax variable, this is declaring it globally (window.ajax) and I think that you don't need it globally...

function runAjax(JSONstring) {
  var params = "data=" + encodeURIComponent(JSONstring), 
      ajax = getHTTPObject();

  ajax.open("POST", "createtrip.php", true);
  ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  ajax.setRequestHeader("Content-length", params.length);
  ajax.setRequestHeader("Connection", "close");
  ajax.onreadystatechange = serverSpeaks;
  ajax.send(params);
}
like image 165
Christian C. Salvadó Avatar answered Oct 22 '22 19:10

Christian C. Salvadó