933

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
8,4304 gold badges46 silver badges47 bronze badges
asked May 31, 2011 at 11:17
10
  • 3
    Can you run the output of JqueryOperation.aspx through a JSON validator and see if it valid JSON Commented May 31, 2011 at 11:19
  • 2
    Like 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}. Commented May 31, 2011 at 11:21
  • 10
    Does the Jqueryoperation.aspx page return (valid) JSON? Commented May 31, 2011 at 11:24
  • 1
    probably your server side code is throwing an exception .. what r u returning in your catch block as the response? Commented May 31, 2011 at 11:28
  • 3
    @Raghav, if the server threw an exception processing the request, then the HTTP return code would be 500. Commented May 31, 2011 at 11:30

14 Answers 14

1266

jQuery.ajax attempts to convert the response body based 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"}
answered May 31, 2011 at 11:31
Sign up to request clarification or add additional context in comments.

Comments

50

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
});
answered Oct 7, 2016 at 3:23

Comments

37

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Jun 15, 2011 at 14:47

Comments

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Jun 29, 2015 at 8:35

Comments

16

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.

answered May 31, 2011 at 11:36

Comments

13

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
31.4k22 gold badges110 silver badges134 bronze badges
answered May 11, 2016 at 2:10

1 Comment

And also if the service method is returning a simple string java object will expect the dataType as text.
9

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Nov 29, 2014 at 23:56

Comments

8

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

Dont remove dataType: 'JSON',

Note: Your response data should be in json format

answered May 1, 2018 at 7:40

1 Comment

The content mentioned in bold is important response must have a body, thanks for saving time.
5

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
31.4k22 gold badges110 silver badges134 bronze badges
answered May 11, 2015 at 5:52

Comments

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Jun 25, 2015 at 14:53

Comments

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Jan 30, 2014 at 7:57

Comments

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!

answered Oct 15, 2018 at 9:48

Comments

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
31.4k22 gold badges110 silver badges134 bronze badges
answered Mar 22, 2016 at 18:57

Comments

-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
10.3k10 gold badges48 silver badges63 bronze badges
answered Apr 21, 2018 at 3:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.