TheEdge TheEdge - 4 months ago 21
jQuery Question

jQuery call to Web API not working


  • .NET 4.61, WebForms, WebAPI 2, C#



I have the following AJAX call to a WebAPI controller:

$.ajax('/api/search', {
type: 'POST',
data: { '': searchText }, // data to submit
done: function (data, status, xhr) {
alert('here');
console.log(data);
$('#search-results').append('status: ' + status + ', data: ' + data);
},
fail: function (jqXhr, textStatus, errorMessage) {
alert('here2');
$('#search-results').append('Error' + errorMessage);
}
});


and the API Contoller code:

public class SearchController : ApiController
{
[HttpPost]
public FindViewModel Find([FromBody] string aSearchText)
{
//Code omitted that does the actual population of the result

//Return them alphabetically
result.Items = result.Items.ToList().OrderBy(r => r.DisplayText).ToList();

return result;
}
}


however I never get into the done or error promises from the original AJAX call. ie no Alerts. Firebug shows a 200 reposonse with the data I expect:

enter image description here

What am I missing here to get into the done/fail promises?

Answer

The issue is .done() and .fail() are not $.ajax() options. You can chain .done() and .fail() to $.ajax() call

$.ajax({
    url: '/api/search',
    type: 'POST',  
    data: { '': searchText }  // data to submit
})
.done(function (data, status, xhr) {
    alert('here');
    console.log(data);
    $('#search-results').append('status: ' + status + ', data: ' + data);
})
.fail(function (jqXhr, textStatus, errorMessage) {
    alert('here2');
    $('#search-results').append('Error' + errorMessage);
});
Comments