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?
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 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:
I reckon your aspx page doesn't return a JSON object. Your page should do something like this (page_load)
Also, try to change your AjaxFailed:
textStatus
should give you the type of error you're getting.jQuery.ajax
attempts to convert the response body depending on the specifieddataType
parameter or theContent-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:
In this case jQuery:
Your server-side code returns HTML snippet with
200 OK
status. jQuery was expecting valid JSON and therefore fires the error callback complaining aboutparseerror
.The solution is to remove the
dataType
parameter from your jQuery code and make the server-side code return:But I would rather suggest returning a JSON response and display the message inside the success callback:
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
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