Buda Gavril
Buda Gavril

Reputation: 21637

make post request with ajax

I try to make a simple request to an api and get back the result, but my request is never launched (I am also looking in fiddler). What am I doing wrong?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button").click(function(){
        makePostRequest("http://www.mocky.io/v2/587ccd320f000081015dxxxx", "dummy_json", null, "post", "json", "div");
    });
});

function makePostRequest(url, data, headers, httpVerb, dataType, elementId){
    alert('click');
    $.ajax({
    url: url,
    type: httpVerb,
    data: data,
    headers: {
        Header_Name_One: 'Header Value One',
        "Header Name Two": 'Header Value Two'
    },
    dataType: 'json',
    success: function (data) {
      alert("success");
    }
}).done(function(msg){
    alert('done');
  });
}
</script>
</head>
<body>

<button id="button">Send an HTTP POST request to a page and get the result back</button>
<div id="div">

</body>
</html>

Upvotes: 2

Views: 2934

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

If you check the request in the console you'll see this error:

SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Header Name Two' is not a valid HTTP header field name.

This is because header keys cannot contain spaces. If you change the header to Header_Name_Two the code works fine:

$(document).ready(function() {
    $("#button").click(function() {
        makePostRequest("http://www.mocky.io/v2/587ccd320f000081015dxxxx", "dummy_json", null, "post", "json", "div");
    });
});

function makePostRequest(url, data, headers, httpVerb, dataType, elementId) {
    $.ajax({
        url: url,
        type: httpVerb,
        data: data,
        headers: {
            Header_Name_One: 'Header Value One',
            Header_Name_Two: 'Header Value Two'
        },
        dataType: 'json',
        success: function(data) {
            alert("success");
        }
    }).done(function(msg) {
        alert('done');
    });
}

Working example

Caveat to the above

You are making a cross domain request. The 'mocky.io' domain does not include CORS headers in their response as you can see in the new error you get from the above fiddle:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

This means that you either need to change the request to retrieve JSONP formatted data - assuming that the third party supports that, which many do not. Alternatively you will need to make the request on the server, not JS.

Upvotes: 3

Related Questions