0

I hope all is well and I appreciate if you can help me or re-direct me to a similar old post because I couldn't find one.

I'm trying to initiate a REST API request and the server will send a JSON response. The request works find but I'm unable to read the JSON output. The status always returns 0.

Here is my code.


<script>
function loadDoc() {

   var xhttp = new XMLHttpRequest();
   xhttp.open("POST", "URL HERE", true);
    xhttp.setRequestHeader("Content-type", "application/json")     
    xhttp.send();
    var response = JSON.parse(xhttp.responseText);
    document.getElementById("demo").innerHTML = response.Result;


}
</script>

I want to print this JSON's result:

{ 
  Meta: { 
    Status: 'Success',
    Debug: ''
  },
  Result: { 
    Count: 2584,
    Error: [],
    Info: [],
    Skipped: [],
    DuplicateResponseCount: 0,
    DuplicateError: null
  }
}

Thanks a lot.

Asma
  • 133
  • 1
  • 1
  • 6

1 Answers1

1

As Pablo said. You are using asynchronous. One option is use get method or just pass a callback to the function.

function _post(url, callback) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", url, true);

  xhttp.onload = function() {
    if (xhttp.status === 200) callback(xhttp.responseText);
    else callback("error");
  };
  xhttp.send();

  return xhttp.responseText;
}

_post("url here", function callback(response) {
  // you can access response in here.
  console.log(response);
});

On your PHP script

<?php
   header("Access-Control-Allow-Origin: *");
hdotluna
  • 5,514
  • 4
  • 20
  • 31
  • Thanks, Lara. I tried the code but it didn't work and I got an "error" message. Previously, I was a able to post the data but I got blank response but now the data wasn't actually posted, though the URL is correct. – Asma Feb 20 '17 at 09:40
  • @Asma you get error because of the xhttp status is not 200. Maybe its 404. I used this for my API. Try using `callback(xhttp.status) in onload function`. :) – hdotluna Feb 20 '17 at 09:56
  • Thanks again. I tried it and it returned "403" "Forbidden", so does that suggest that the server is rejecting my request? – Asma Feb 20 '17 at 10:08
  • @Asma did you try to add header in PHP? – hdotluna Feb 21 '17 at 01:58
  • Thanks Lara. I investigated further about the same origin policy and it appears that it was causing the problem. I found out that the server supports JSONP so I'm trying now in this direction. Many thanks for your help. – Asma Feb 21 '17 at 04:46
  • @Asma You're welcome. I'm glad I helped you :) Happy coding. – hdotluna Feb 21 '17 at 04:52