855

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?

Arsen Khachaturyan
  • 6,472
  • 4
  • 32
  • 36
Pankaj Mishra
  • 19,129
  • 14
  • 63
  • 102
  • 2
    Can you run the output of JqueryOperation.aspx through a JSON validator and see if it valid JSON – parapura rajkumar May 31 '11 at 11:19
  • 1
    Like http://jsonlint.com/ . You also have to check the parameters you send. Currently you have not set any parameter name. If the parameter is `TwitterId`, then you have to pass an object to `data`, not a string: `data: {TwitterId: row}`. – Felix Kling May 31 '11 at 11:21
  • 7
    Does the Jqueryoperation.aspx page return (valid) JSON? – Salman A May 31 '11 at 11:24
  • 1
    probably your server side code is throwing an exception .. what r u returning in your catch block as the response? – Raghav May 31 '11 at 11:28
  • 3
    @Raghav, if the server threw an exception processing the request, then the HTTP return code would be 500. – StuperUser May 31 '11 at 11:30
  • I dont understand why you have to use both POST, and GET?besides twitterId should be in double quotes not single, – Val May 31 '11 at 11:37
  • @Val: its perfectly OK to have Query String parameters along with POST data. – Salman A May 31 '11 at 11:43
  • I didnt say it wasn't I am just saying why use both and complicate things, simple is better that all :) – Val May 31 '11 at 13:03
  • This answer may not be complete. Just now I validated my JSON at `jsonlint.com`, it explicitly says that it is a vaild json, but still "error" event is fired, with `xhr.status` 200. what other reasons can be there? – Ramesh Pareek Jun 30 '16 at 10:18
  • Can anyone help with this problem? https://stackoverflow.com/questions/49122972/hide-jquery-elements-in-an-ajax-function?noredirect=1#comment85410225_49122972 – TRS7 Mar 10 '18 at 17:26

16 Answers16

1176

jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.


Your AJAX code contains:

dataType: "json"

In this case 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. […] an empty response is also rejected; the server should return a response of null or {} instead.

Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.

The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:

Content-Type: application/javascript

alert("Record Deleted");

But I would rather suggest returning a JSON response and display the message inside the success callback:

Content-Type: application/json

{"message": "Record deleted"}
Salman A
  • 229,425
  • 77
  • 398
  • 489
  • 1
    Thanks for your response can you please tell me one thing how can i return json value from code behind. I am using Asp.net with C#. This solved my issue but can please also let me know this thing also. – Pankaj Mishra May 31 '11 at 11:37
  • Use the [Json Class](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.aspx) may be? – Salman A May 31 '11 at 11:40
  • 1
    @Pankaj: it is better if you post it as another question. But short answer: two ways of doing this (i) instead of `$.ajax` you can try `$.getScript`. Inside the server side C# script just put `alert('Record Deleted');` (no ` – Salman A Jun 01 '11 at 09:13
  • (ii) do a `Response.Write("{\"success\": 1, \"message\": \"Record Deleted\"}");` in your server side C# script. Write your `$.ajax` success handler like this: `function AjaxSucceeded(result) {alert(result.success + ' ' + result.message);}` – Salman A Jun 01 '11 at 09:16
  • For me, this solved my problem with my webmethod retuning okay, but getting an 'invalid label' in firefox.. i think it has to do with jsonp and .net. took me a while to find this post.. – hanzolo May 18 '13 at 17:43
  • I was befuddled there for a second. HTTP 200 - OK generally means that the response was a success. This is like saying "Error - the action was a success. THAT SHOULD NEVER BE A SUCCESS. just' sayin'" Nice catch @SalmanA – Eon Sep 25 '14 at 07:28
  • Wow that works perfectly! Just add this to your controller: `format.json { render json: @mymodel.to_json, status: :ok }` – Avishai Dec 19 '14 at 18:36
  • 3
    This answer may not be complete. Just now I validated my JSON at jsonlint.com, it explicitly says that it is a vaild json, but still "error" event is fired, with xhr.status 200. what other reasons can be there? – Ramesh Pareek just now edit – Ramesh Pareek Jun 30 '16 at 10:20
  • @RameshPareek what is the error? The error event handler is supplied with three arguments. Can you post them? – Salman A Jun 30 '16 at 11:34
  • yes the xhr.status parameter of the error event handler returned `parseerror`. later the problem was solved. Although jsonlint was accepting it as a valid json, I had used the JSON PRETTY PRINT option while encoding the json. removing this option made it work. for future visitors, some of us add the
     
    tags around the encoded json, obviously it'll create a problem, because though the browser doesn't show those
     tags, they do show up in the ajax response
    – Ramesh Pareek Jul 01 '16 at 15:31
  • 3
    Or you can just delete the "dataType:json" parameter – Piero Alberto Feb 12 '18 at 08:42
  • 2
    I've run into this same problem without specifying a datatype when using `$.post`. In this case, _jquery guesses a datatype, then errors when it fails to parse_. This is a really nasty, hard-to-find gotcha. I fixed it by setting the datatype to `"text"`. – Mashmagar Mar 31 '19 at 18:01
  • Hi there, I've got same error. I've tried to above solutions, but error is still exist. My Ajax call; $.ajax({ type: 'GET', url: url, dataType: 'jsonp', cors: true, contentType: 'application/json;charset=UTF-8', accepts: 'application/json;charset=UTF-8', secure: true, headers: { 'Access-Control-Allow-Origin': '*', }, beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("")); }, – Ibrahim Ates May 26 '21 at 13:19
  • When I delete dataType then I've got CORS error. any suggest? thanks – Ibrahim Ates May 26 '21 at 13:21
34

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
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jaketrent
  • 1,143
  • 11
  • 25
  • 1
    Based on JQuery documentation, Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml. So it will try to covert text to json first, and if failed, then just treated as text? – anIBMer Mar 10 '16 at 01:53
31

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
});
Philippe Genois
  • 429
  • 4
  • 6
24

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Corvin
  • 940
  • 8
  • 16
  • 1
    Thanks Peter, I had the same issue, and the warning message on browser console is confused for me,. As far as i know the CORS blocks the send request (using options method negotiation) , no makes sense that block after the operation after has been completed . Maybe is a custom browser behaviour..I tested with Firefox. Thanks, your solution solved my problem. – danipenaperez Jun 18 '19 at 09:00
15

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.

LeftyX
  • 34,522
  • 20
  • 128
  • 188
12

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
8

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Bilel omrani
  • 91
  • 1
  • 5
4

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;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Terry Lin
  • 2,082
  • 16
  • 19
4

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 { });
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
4

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); }
    });
}
Stephen Rauch
  • 40,722
  • 30
  • 82
  • 105
Rakesh Kumar
  • 55
  • 1
  • 9
  • I'm seeing the same thing. Empty response with a 200 code is still triggering the error handler. – doublejosh Apr 30 '19 at 01:11
  • I was having the same Issue, but I solved it when I came into account that I was pressing a button inside a form that was submitting rather than excecuting the AJAX by itself. I solved it by using $("#my-selector").click(function (e) { e.preventDefault(); ...ajax code... }); – benjamingranados Nov 16 '20 at 15:43
3

See this. It's also a similar problem. Working I tried.

Dont remove dataType: 'JSON',

Note: Your response data should be in json format

Inderjeet
  • 1,109
  • 1
  • 10
  • 25
2

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Paul
  • 43
  • 4
2

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!

Fabian von Ellerts
  • 3,261
  • 28
  • 31
1

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
-1

Your script demands a return in JSON data type.

Try this:

private string test() {
  JavaScriptSerializer js = new JavaScriptSerializer();
 return js.Serialize("hello world");
}
petezurich
  • 6,779
  • 8
  • 29
  • 46
Kashif Faraz
  • 181
  • 4
  • 15
-9

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.

Salman Riaz
  • 105
  • 1
  • 6