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

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?

This question is related to javascript jquery asp.net ajax json

The answer is


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.


I have the similar problem but when I tried to remove the datatype:'json' I still have the problem. My error is executing instead of the Success

function cmd(){
    var data = JSON.stringify(display1());
    $.ajax({
        type: 'POST',
        url: '/cmd',
        contentType:'application/json; charset=utf-8',
        //dataType:"json",
        data: data,
        success: function(res){
                  console.log('Success in running run_id ajax')
                  //$.ajax({
                   //   type: "GET",
                   //   url: "/runid",
                   //   contentType:"application/json; charset=utf-8",
                   //   dataType:"json",
                   //   data: data,
                   //  success:function display_runid(){}
                  // });
        },
        error: function(req, err){ console.log('my message: ' + err); }
    });
}

Your script demands a return in JSON data type.

Try this:

private string test() {
  JavaScriptSerializer js = new JavaScriptSerializer();
 return js.Serialize("hello world");
}

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.


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
});

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;

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 to change your AjaxFailed:

function AjaxFailed (XMLHttpRequest, textStatus) {

}

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


If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...

jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!


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.


See this. Its also similar problem. Working i tried.

Dont remove dataType: 'JSON',

Note: echo only JSON Formate in PHP file if you use only php echo your ajax code return 200


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
});

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.


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 { });
}

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...


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?