0

I am trying to do http post using JavaScript but something is going wrong.. I already searched a bit, and found two snippets but none is working.

The first attempt:

<!DOCTYPE html>
<html>
<head>
<script>

function changetext(id) {

    var xmlhttp = new XMLHttpRequest();
    var url = "http://10.21.6.128:1234/test/test2/teste3/teste4";
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }
    var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});

    xmlhttp.send(parameters);


}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>

In this attempt, there is no JSON being thrown, at my server I get a null input.. I used fiddler to check it, and nothing is being posted..

I searched a few more and found this example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

    JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "http://10.21.6.128:1234/teste/teste2/teste3/teste4",
        type: "POST",
        data: {"Test":"2222","Code":"OP1","Partner":"Test","Prod":"Prod"},
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

In this case I get a bad request, error 400. Can someone help me?

Thanks alot in advance ;)

TiagoM
  • 3,458
  • 4
  • 42
  • 83
  • Looks like you are making request to diffrent server, in that case change `dataType:'json'` to `dataType:'jsonp'` and try. – Dharmesh Patel May 13 '14 at 13:00
  • @DharmeshPatel — You can't make a POST request with JSONP. – Quentin May 13 '14 at 13:02
  • @DarkLink — The first example looks as though it should work. Could you show a screenshot of fiddler? (The second example isn't even attempting to send JSON, its doing a form encoded request). – Quentin May 13 '14 at 13:03
  • What does the JavaScript console in your browser say? – Quentin May 13 '14 at 13:04
  • First example misses a semicon before `var parameters = JSON.stringify` (line 11 of script). Second example is valid, but `400 Bad Request The request cannot be fulfilled due to bad syntax` – John Priestakos May 13 '14 at 13:06
  • Missing semi-colon isn't a problem because JS has semi-colon insertion, it is just bad style. The Bad Request is almost certainly because, as I mentioned, it isn't posting JSON. – Quentin May 13 '14 at 13:09
  • Afaik you can also not do a POST cross-domain (unless CORS headers are set properly). Not sure whether this is cross-domain though? – christian314159 May 13 '14 at 13:20
  • It isn't possible to tell from the question. That's one reason I asked for a copy of log from the JavaScript console. – Quentin May 13 '14 at 13:21
  • Its not cross-domain I guess, because I am at localhost making a request to localhost, but I am using the IP of my machine, so fiddler can sniff. – TiagoM May 13 '14 at 13:21
  • Cross origin can cause problems. The domain is only one part of that. As previously requested, please show us exactly what Fiddler shows and what the JS console of your browser shows. – Quentin May 13 '14 at 13:27
  • I can't get the JS Console to show anything at google chrome, it appears all blank. And here is the image with the what fiddler sniffed http://i58.tinypic.com/2q9bd37.png . As you see there is no body.. I also clicked on "JSON" tab and there was nothing there – TiagoM May 13 '14 at 13:36
  • That is an OPTIONS request, not a POST request. You are making a pre-flight CORS check. I'm amazed the JavaScript console isn't complaining about a Same Origin Policy violation. – Quentin May 13 '14 at 13:58
  • [Duplicate](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Quentin May 13 '14 at 13:59

2 Answers2

0

It appears the POST request never gets sent due to Same Origin Policy. Your fiddler screenshot shows an OPTIONS request, which is expected in a cross domain situation. The OPTIONS request is used to find out if the target server supports Cross Origin Resource Sharing (CORS). This is known as a preflight request.

In order for a request to be considered "same domain", the protocol, domain and port all must match.

If you control the target server, you can enable CORS by outputting the response header:

Access-Control-Allow-Origin: *

Note: the * denotes all domains are permitted, you can narrow it to a specific domain if more suitable.

Also, the second code sample in the question will never send JSON, regardless of CORS.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Thanks for your reply, I added the following header on XMLHttpRequest: "xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");" But still its making an option request, not a POST Request . I am using google chrome, can you help me? Thanks ;) – TiagoM May 13 '14 at 15:22
  • You can't set it as a request header. It must be a response header, that is output and returned by the remote server. If you don't have access to modify the server configuration then you can't use CORS unfortunately. – MrCode May 13 '14 at 15:25
  • I have access to the server itself, its a ServiceHost, a self hosted REST service waiting for a JSON Request and replies also in JSON. How do I add that responde header ? thanks – TiagoM May 13 '14 at 15:35
  • See if this is any help: http://blogs.microsoft.co.il/idof/2011/07/02/cross-origin-resource-sharing-cors-and-wcf/ – MrCode May 13 '14 at 15:44
-1

Add jQuery to first example and try following,

var parameters = $.param({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});

instead of,

var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});
Dharmesh Patel
  • 1,881
  • 1
  • 11
  • 12
  • The server is expecting JSON, not application/x-www-form-urlencoded data. The second example sends application/x-www-form-urlencoded data and that triggers a 400 error. – Quentin May 13 '14 at 13:16
  • Hi Dharmesh patel, thanks for your help but didn't work.. I still gets null at server side, there is no JSON on the request, I watched at fiddler – TiagoM May 13 '14 at 13:20
  • Try `data: { Test: "2222", Code: "OP1", Partner: "Test", Prod: "Prod" },` – John Priestakos May 13 '14 at 13:22
  • That didn't work also John Priestakos, I used that example on my second snippet but I am still getting bad request (error 400) – TiagoM May 13 '14 at 13:26
  • Of course it didn't work. You are trying to send JSON. This entire answer is about sending something other than JSON. – Quentin May 13 '14 at 13:28
  • We need the console.log or other log – John Priestakos May 13 '14 at 13:28
  • @Quentin so you are saying that the title is wrong ? – John Priestakos May 13 '14 at 13:29
  • @JohnPriestakos — No. The question is asking how to post JSON. The first code in the question (should) send JSON. The second code in the question doesn't send JSON and gets a Bad Request error. This answer is about changing the first script does it doesn't post JSON like the second script. – Quentin May 13 '14 at 13:30