Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  128] [ 2]  / answers: 1 / hits: 6978  / 10 Years ago, sat, may 10, 2014, 12:00:00

I am currently working on ASP.NET WebApi and Angularjs



WebApi have a method



 [System.Web.Http.AcceptVerbs(POST)]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}


And I have to call this method from client side.



When I call this method using Ajax, it's not working, the method parameter searchDetail is always null if I use Ajax.



$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: json,
headers: {
'Content-Type': application/json; charset=utf-8
}
}).success(function (response) {
return response;

}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})


But when I call that method via HTTP request, it is working.



 $http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': application/json; charset=utf-8
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})



Why? What is the difference between them? Why is Ajax not working and HTTP is?



More From » ajax

 Answers
5

jQuery's ajax() sends the data with Content-type: x-www-form-urlencoded.

Angular's $http sends the data with Content-type: application/json


Your server obviously expects JSON, but you set up the $.ajax() call incorrectly for that.


According to the docs:



  • The method property doesn't seem to exist.

  • The type property is supposed to determine the type of the request (e.g. 'GET', 'POST', etc.).

  • In order to change the default content-type to application/json you can use the contentType property.




I have not tried it myself, but something like this should work:


$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});

[#45408] Friday, May 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;