Converting curl cmd to jQuery $.ajax()

krisrak picture krisrak · Nov 22, 2013 · Viewed 71.6k times · Source

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 ?

Answer

krisrak picture krisrak · Nov 24, 2013

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");
    }
});