Aleksa999
Aleksa999

Reputation: 11

Reading JSON Response with Javascript - Problem

I'm sending data to the server using JSON and post method, but I can't read the response from the server. Here's my code:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://staging.smartenupcs.com/api/v1/licenses/create", true);
xhr.setRequestHeader("Smartenup-API-KEY", "webflow.c407d56c5ab23115af0075+DzDMrMtWZENCoct9Pa7DUA54mIgP8c9o");
var jsonStr = JSON.stringify({
  "first_name": "Bla",
  "last_name": "Blabla",
  "email": "[email protected]",
  "product_name": "webflow_essentials",
  "order_id": 21811,
  "voucher": null

});
xhr.send(jsonStr);

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var myObj = JSON.parse(xhr.responseText);
    alert(myObj);
  }
};

I tried many options but no success.

I hope someone can help, thank you in advance

Upvotes: 1

Views: 71

Answers (3)

Guru1988
Guru1988

Reputation: 492

I would recommend using fetch API instead of the XMLHttpRequest object.

function postData(url = `UR_URL_HERE`, data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
}

Upvotes: 0

Atul Sharma
Atul Sharma

Reputation: 10675

There are no issues with the code.

The issue is with Cross-Origin Requests. You seems to be hitting API from domain other than staging.smartenupcs.com most probably localhost.

Just add cross-origin headers to server and it will work.

PS: It will work without cross-origin headers when your frontend code and api are hosted on same domain.

enter image description here

Upvotes: 1

Nikhil Lende
Nikhil Lende

Reputation: 129

Please check at Server side for Access-Control-Allow-Origin header. Also check for OPTIONS preflight request of that api/action. After that check for api response status and your response checking condition.

Upvotes: 0

Related Questions