2

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>
Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • 1
    did you see any error in console? – K D Jan 18 '17 at 09:24
  • no, I don't see any error in the console – Buda Gavril Jan 18 '17 at 09:28
  • is it a cross domain call you are making? check this link http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain – K D Jan 18 '17 at 09:30
  • ` – kosmos Jan 18 '17 at 09:30
  • Tried this myself. If you handle the "error" callback, as per the jquery docs https://api.jquery.com/jQuery.ajax/ (i.e. I used `error: function( jqXHR, textStatus, errorThrown ) { alert("error:" + textStatus + " " + errorThrown); }` then you get "SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Header Name Two' is not a valid HTTP header field name." – ADyson Jan 18 '17 at 09:35

1 Answers1

3

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Yes, with your example works. But I've updated the code to add a callback for done and for fail. The interesting part is that the fail callback is executed, even if I see in the fiddler that the request has status 200. Do you have any ideea why? – Buda Gavril Jan 18 '17 at 09:47
  • But I-me configured mocky to add this header in the response> – Buda Gavril Jan 18 '17 at 09:53
  • HTTP/1.1 200 OK Server: Cowboy Connection: close Content-Type: application/json; charset=utf-8 Access-Control-Allow-Origin: * Date: Wed, 18 Jan 2017 09:52:50 GMT Via: 1.1 vegur This is a part from the response – Buda Gavril Jan 18 '17 at 09:53
  • Ok, that should be fine then. If you have added a `fail()` handler you can use the parameters passed to it to diagnose the error. – Rory McCrossan Jan 18 '17 at 09:54
  • hmm... something is strange: I've added this: .fail(function(msg){alert(JSON.stringify(msg))}) and in the alert I see something like: "status" : 200, "StatusText" : "OK", "readyState" : 4... This means that the requested ended with success, right? If yes, then why fail callback is triggered? if no, then why the status 200? – Buda Gavril Jan 18 '17 at 10:00
  • Could you setup an example of whats happening in another fiddle? – Rory McCrossan Jan 18 '17 at 10:04
  • I've got it, I was having dataType json and the response was in xml – Buda Gavril Jan 18 '17 at 10:17
  • Haha yep, was just about to comment. Glad you got it working – Rory McCrossan Jan 18 '17 at 10:19