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?
You simply have to remove the dataType: "json" in your AJAX call
Your script demands a return in JSON data type.
Try this:
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:
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
If you always return JSON from the server (no empty responses),
dataType: 'json'
should work andcontentType
is not needed. However make sure the JSON output...jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
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.Use the following code to ensure the response is in JSON format (PHP version)...