20

I'm trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500

I have a curl command working that looks like this:

curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api

I tried ajax like this, but it is not working:

$.ajax({
    url: "http://www.example.com/api",
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: {foo:"bar"},
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});

What am I missing ?

krisrak
  • 12,882
  • 3
  • 32
  • 46
  • 3
    Unless the API supports cross domain request with CORS, you can't! You can however do the ajax call to the serverside, and then let the server do the cURL stuff. – adeneo Nov 22 '13 at 22:32
  • @adeneo I'm using custom packaging that does not block cross domain request, assuming this is same origin, how do I get this to work ? – krisrak Nov 22 '13 at 22:36

1 Answers1

39

By default $.ajax() will convert data to a query string, if not already a string, since data here is an object, change the data to a string and then set processData: false, so that it is not converted to query string.

$.ajax({
    url: "http://www.example.com/api",
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: '{"foo":"bar"}',
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});
krisrak
  • 12,882
  • 3
  • 32
  • 46
  • 2
    Thanks, this answered my question, here http://stackoverflow.com/questions/30992688/creating-task-using-wunderlist-api/31015511#31015511 – damuz91 Jun 24 '15 at 00:08