Home Ask Login Register

Developers Planet

Your answer is one click away!

Xerphiel February 2016

AJAX, jQuery HTTP Post, no data being recieved

I've looked at many similar questions on here, but I am unable to get to the bottom of this issue.

I've built a Web API, and if I post at it using curl as follows:

curl -i -H "Content-Type: application/json" -X POST -d '{"password":"abcd"}' http://<ip>:5000/api/v1.0/state

My API receives the message and records:

<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
{u'password': u'abcd'}
192.168.1.100 - - [08/Feb/2016 21:04:32] "POST /api/v1.0/stateHTTP/1.1" 200 -

So far so good....

I've built a webpage with the following code (I am brand new to web dev), which I am using to post against this API:

function myFunction() {

$.ajax({
    url: "http://" + document.domain + ":5000/api/v1.0/state",
    method: "POST",
    dataType:"json",
    data: {"password" : "John"},
    success: function(data){
        alert(data);
    }
});

}

When calling this function, the post is clearly recieved by my API, but without any data:

<Request 'http://<ip>:5000/api/v1.0/state' [POST]>
None
192.168.1.120 - - [08/Feb/2016 21:09:53] "POST /api/v1.0/state HTTP/1.1" 200 -

I've tried using a $.post method:

$.post(
"http://" + document.domain + ":5000/api/v1.0/state",
JSON.stringify({"password" : "password" }) ,
function(data) {
    alert("Response: " + data);
 }
);

And I get the same result.

EDIT: Tried using the following code, as suggested by an answer below:

$.ajax({
   url: "http://" + document.domain + ":5000/api/v1.0/state",
   method: "POST",
   dataType:"json",
   contentType:'application/json',
   data: JSON.stringify({"password" : "John"}),
   success: function(data){
       alert(data);
   }

});

And I receive an OPTIONS API response:

192.168.1.120 - - [08/Feb/2016 21:31:28] "OPTIONS /api        

Answers


Patrick Evans February 2016

By your curl snippet it looks like your endpoint is expecting a JSON request payload. jQuery does not set a content-type request header of application/json, so you have to actually tell it to do so:

$.ajax({
    url: "http://" + document.domain + ":5000/api/v1.0/state",
    method: "POST",
    dataType:"json",
    contentType:'application/json',
    data: JSON.stringify({"password" : "John"}),
    success: function(data){
        alert(data);
    }
});

Also note if this is being used on a different domain, meaning not "http://" + document.domain + ":5000, you may end up hitting a CORS issue.

Post Status

Asked in February 2016
Viewed 1,468 times
Voted 10
Answered 1 times

Search




Leave an answer


Quote of the day: live life