t2k32316
t2k32316

Reputation: 993

jQuery not handling JSON response from AJAX POST

Updated: I'm posting HTML FORM data but expecting to receive JSON data. I am not trying to POST JSON data.

I am trying to get a JSON response back from doing a HTML FORM POST request. I have successfully received a JSON back when using a simple HTML FORM POST request (i.e. not AJAX). My JSON response from the HTML FORM POST is this:

{"success":true,"data":1234567}

The problem occurs when I try to handle the request and response with jQuery's .ajax().

$.ajax({
    type: "POST",
    url: URL,
    data: data1,
    dataType: "json",
    success: function(data, textStatus, jqXHR) {
        alert ("success");
    },
    error: function(xhr, status, error) {
        alert ("Error: " + error);
    }
});

After running the above code and debugging in Firebug, it appears that the POST request is going through, but something is going wrong on the handling of the response. Firebug tells me the following regarding the HTTP response from the POST request:

Response Headers
Cache-Control   private
Content-Length  31
Content-Type    application/json; charset=utf-8
...

So it appears that the 31 bytes of data is being sent. However, when debugging the actual Javascript, the error function gets called and the xhr object is this:

Object { readyState=0, status=0, statusText="error"}

I know the jQuery.ajax() document states that "In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown." However, I believe my JSON is valid as I have checked it at jsonlint.com.

What else could be going wrong?

Upvotes: 4

Views: 9351

Answers (4)

Some times Jquery return Internal Error 500 for currectly data.

There is example for read the same json data withour error

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/products/3", true);
xhr.onload = function(){
    console.log(xhr.responseText);
};
xhr.send();

Upvotes: 0

Todd Moses
Todd Moses

Reputation: 11029

I was having the same problem. It seems that this is an issue with Cross Domain.

Finding this SO answer: https://stackoverflow.com/a/7605563/154513

helped me.

Upvotes: 0

Johnny Craig
Johnny Craig

Reputation: 5002

your getting an error because data1 is not formatted in json, so when it receives the data it gets a parse error. data1 needs to be formatted:

data1={"apikey":apikey,
        "firstname":fName
      }

Upvotes: 0

hspain
hspain

Reputation: 17568

It looks to me like you are getting a server error. I would check the status code of the response and fix whatever is causing the request to fail on the server.

Upvotes: 1

Related Questions