Search code examples
javascriptjqueryajaxresponse

Return response in JSON from AJAX command


How can I get native javascript AJAX to return response in JSON rather than 'text over HTML'?

Description: In jquery, the following AJAX function returns JSON data, which is what we needed.

JQUERY CODE

 //ajax Handler function through which I set default attribute and send request function defined separately to send request to server 
ajaxHandler = {
  defaultAttributes: {
    type: 'GET',
    url: 'index.php/request',
    datatype: 'json',
    data: {},
    success: null,
    error: function(data) {
      errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
    },
    timeout: function() {
      errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
    }
  },
  sendRequest: function(attributes) {
    //i perform here through jquery 
    $.ajax(attributes);
  }

Now, that the code is changed to native javascript AJAX, in which I am making a 'application/json;charset=UTF-8' request, I am getting the response back in 'text over HTML' instead of JSON.

NATIVE JAVASCRIPT

var xmlhttp = new XMLHttpRequest();
                                xmlhttp.onreadystatechange = function () {
                                        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
          attributes.success(attributes.data);
                                        }
                                }
                                xmlhttp.open(attributes.type, attributes.url);
                                xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                                xmlhttp.send((attributes.data));

Comparing the two in Chrome Developer Tools, under Network tab, here is what I get for Jquery AJAX:

Remote Address:127.0.0.1:80
Request URL:http://localhost/1412-DressingAphrodite/Webapp/index.php/request/getallfeatures
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Cookie:PHPSESSID=tivt0hi9oqtbtjem7m9d0emhr1
Host:localhost
Pragma:no-cache
Referer:http://localhost/1412-DressingAphrodite/Webapp/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
Connection:Keep-Alive
Content-Type:application/json; charset="UTF-8"
Date:Fri, 30 Jan 2015 04:43:07 GMT
Keep-Alive:timeout=5, max=18
Server:Apache/2.4.10 (Ubuntu)
Transfer-Encoding:chunked
X-Powered-By:PHP/5.5.12-2ubuntu4.1

And here is what I get in Native Javscript AJAX:

Remote Address: 127.0.0.1:80
Request URL: http://localhost/1412-Dre/Webapp/index.php/request/getallfeatures
Request Method: GET
Status Code: 403 Forbidden
Request Headersview source
Accept: /
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json;charset=UTF-8
Cookie: PHPSESSID=tivt0hi9oqtbtjem7m9d0emhr1
Host: localhost
Pragma: no-cache
Referer: http://localhost/1412-Dre/Webapp/ User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36
Response Headersview source
Connection: Keep-Alive
Content-Length: 1063
Content-Type: text/html
Date: Fri, 30 Jan 2015 06:40:26 GMT
Keep-Alive: timeout=5, max=90
Server: Apache/2.4.10 (Ubuntu)
X-Powered-By: PHP/5.5.12-2ubuntu4.1

Note the 'Content-Length' value of 1063. Im not sure whether thats the problem. So, to repeat myself, how can I get native javascript AJAX to return response in JSON rather than 'text over HTML'?


Solution

  • If your response is valid JSON, try the following:

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            var jsonResponse = JSON.parse(xmlhttp.responseText);
    
            console.log(jsonResponse);
        }
    }