Home » Jquery » Ajax request returns 200 OK, but an error event is fired instead of success

Ajax request returns 200 OK, but an error event is fired instead of success

Posted by: admin November 2, 2017 Leave a comment

Questions:

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event. I tried a lot of things, but I could not figure out the problem. I am adding my code below:

jQuery Code

var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});
function AjaxSucceeded(result) {
    alert("hello");
    alert(result.d);
}
function AjaxFailed(result) {
    alert("hello1");
    alert(result.status + ' ' + result.statusText);
}

C# code for JqueryOpeartion.aspx

protected void Page_Load(object sender, EventArgs e) {
    test();
}
private void test() {
    Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}

I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?

Answers:

Your Ajax request contains the following setting:

dataType: "json"

The documentation states that jQuery:

Evaluates the response as JSON and returns a JavaScript object. (…)
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown.

This means that if the server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".

Solution: Make sure that the server returns valid JSON. It is worth noting that an empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.

You can check whether a JSON is valid or not on jsonlint.com.

Questions:
Answers:

I’ve had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Questions:
Answers:

You simply have to remove the dataType: “json” in your AJAX call

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'json', //**** REMOVE THIS LINE ****//
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Questions:
Answers:

I reckon your aspx page doesn’t return a JSON object.
Your page should do something like this (page_load)

var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);

Response.Write(OutPut);

Also, try and change your AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

textStatus should give you the type of error you’re getting.

Questions:
Answers:

This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP’s.

In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:

response.writeHead(200,
          {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "http://localhost:8080"
        });

It literally cost me an hour of banging my head against the wall. I am feeling stupid…

Questions:
Answers:

You just have to remove dataType: 'json' from your header if your implemented Web service method is void.

In this case, the Ajax call don’t expect to have a JSON return datatype.

Questions:
Answers:

I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:

public JsonResult ActionName(){
   // Your code
   return Json(new { });
}

Questions:
Answers:

I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.

Then in your Ajax call please mention dataType='text'.

It will resolve the problem.

Questions:
Answers:

Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can’t handle requests from one to the other.

Questions:
Answers:

Use the following code to ensure the response is in JSON format (PHP version)…

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;

Questions:
Answers:

I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.

Questions:
Answers:

Try following

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: { "Operation" : "DeleteRow", 
            "TwitterId" : 1 },
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

OR

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow&TwitterId=1',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Use double quotes instead of single quotes in JSON object. I think this will solve the issue.