Donavon Lerman
Donavon Lerman

Reputation: 433

Convert jQuery .ajax with dataType: json to plain javascript

I can use jQuery for fast drafting / prototyping but I can not YET implement it on our production servers.

I need assistance with getting the plain javascript version of the following to work. In the plain javascript version submit.php is not receiving the json data.

Original jQuery:

  $.ajax({
      type: "POST",
      url: "submit.php",
      data: json,
      dataType: "json",
      success: function(json){
        alert('success');
      }
  });

Plain javascript:

  var xmlhttp;

  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.open("POST","submit.php",true);
  xmlhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
  xmlhttp.send(json);
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {                 
      alert('success');
    }
  }

Upvotes: 0

Views: 822

Answers (1)

Donavon Lerman
Donavon Lerman

Reputation: 433

I found an answer!! Hope others find it useful.

jQuery adds default headers (http://api.jquery.com/jquery.ajax/):

Content-Type: 'application/x-www-form-urlencoded; charset=UTF-8'
X-Requested-With: XMLHttpRequest

jQuery converts the data (http://api.jquery.com/jquery.ajax/):

"It is converted to a query string, if not already a string."

jQuery then sends the request as a regular POST query string.

I found the needed snippet to convert from json to a POST query string in Plain JavaScript here: https://github.com/oyvindkinsey/easyXDM/issues/199

Here is the updated plain JavaScript code:

var xmlhttp;

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("POST","submit.php",true);
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    alert('success');
  }
}

xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");

var pairs = [];
for (var key in json) {
  pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(json[key]));
}

var data = pairs.join("&");

xmlhttp.send(data);

Upvotes: 1

Related Questions