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": "bla@gmail.com",
  "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

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.

Working with JSON, The JSON Parse error is a specific type of SyntaxError object. When Should You Use It? While most developers are probably intimately familiar� To resolve the “the response is not a valid JSON response” or mixed content error, navigate to Settings > SSL. This will open the plugin’s settings. This will open the plugin’s settings. Now click on the Settings tab.

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.

JavaScript Error Handling, parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format. The JSON.parse() method can optionally transform the � console.log(JSON.parse(response)); You'll get output as Object {result: true, count: 1}. In order to use that object, you can assign it to the variable, let's say obj: var obj = JSON.parse(response); Now by using obj and the dot(.) operator you can access properties of the JSON Object. Try to run the command. console.log(obj.result);

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
}

JSON.parse(), What is JSON. JSON stands for JavaScript Object Notation. Parsing JSON Data in JavaScript If the given string is not valid JSON, you will get a syntax error. to return the json in xhr2. xhr.onload=function(){ console.log(this.responseJSON()); } EDIT . If you plan to use XHR with arraybuffer or other response types then you have to check if the response is a string. in any case you have to add more checks e.g. if it's not able to parse the json.

JavaScript JSON parse() Method, Later, you can then read the information with the JSON.parse() method and work with the data as needed. We'll look at a JSON object that we� A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.

JavaScript JSON Parsing, parseJSON( json )Returns: String or Number or Object or Array or Boolean version To parse JSON strings use the native JSON.parse method instead. This problem is often seen when injecting JSON into a JavaScript file from a server-side� Because JSON is derived from the JavaScript programming language, it is a natural choice to use as a data format in JavaScript. JSON, short for JavaScript Object Notation, is usually pronounced like the name “Jason.” To learn more about JSON in general terms, read the “An Introduction to JSON” tutorial.

How To Work with JSON in JavaScript, To access the JSON object in JavaScript, parse it with JSON.parse() , and access it via “.” or “[]”. JavaScript. <script> var data = '{"name":� The JavaScript exceptions thrown by JSON.parse() occur when string failed to be parsed as JSON.. Message SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse

Comments
  • have you tried checking what "xhr.status" is? probably not 200?
  • Use the browsers debugging tools to inspect the network call being made and see if you're getting the response you expect.