Reputation: 1455
I have created ASP.NET Web API service and hosted it. The service is working fine when I checked with Fiddler but when I give call to the same via jQuery ajax it doesn't work, nor am I getting any error. I tried calling different API methods but getting the same issue
WebAPI:
namespace WebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public string Post(Interview Interview)
{
return "Date: " + Interview.DateOfSurvey + " \n rdInterviewObtained: " + Interview.rdInterviewObtained + "\n txtWhowasinterOther: " + Interview.txtWhowasinterOther;
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Ajax Call :
$("#btnSave2").click(function () {
var person = { DateOfSurvey: '01-01-2012', rdInterviewObtained: 'N', txtWhowasinterOther: 'N' };
alert('inside button click');
jQuery.support.cors = true;
$.ajax({
url: "http://url/api/Values",
type: 'GET',
//data: person,
//dataType: 'json',
success: function (data) {
alert('success');
},
error: function (x, y, z) {
alert('error');
alert(x + '\n' + y + '\n' + z);
}
});
});
Upvotes: 1
Views: 3675
Reputation: 1039398
It seems that you are calling this AJAX method in the .click handler of some button. If this is a submit button make sure you cancel the default action by returning false from the callback, otherwise your AJAX call might never have the time to execute.
Another problem with your code is that you have instructed jQuery to use CORS, but for this to work you need your Web API to send the proper response headers. Here's an article
you might read which illustrates how this could be achieved on the server.
jQuery.support.cors = true;
$('#btnSave2').click(function () {
$.ajax({
url: 'http://url/api/Values',
type: 'GET',
success: function (data) {
alert('success');
},
error: function (x, y, z) {
alert('error');
alert(x + '\n' + y + '\n' + z);
}
});
return false;
});
Upvotes: 2