I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have “1” in response but my ajax method always goes to error function.
Why is it so?
2
Answers
In your AJAX call it should be
dataType: "json"
and notdatatype: "jsondata"
. You can refer to the docsAlso use
@Url.Action
tag in yoururl
call:url: '@Url.Action("postdata", "widget")'
For a small test, I have used the following
AJAX
call to the same controller method that you have posted and I am getting the correct result:Output:
Change the Ajax request to the following :
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don’t have to change the URls when going live