Request for JSON content from URL

Hi,

I am new to Javascript

I am working on an assignment where I’m suppose to request for JSON content.

================

let OrgURL =’’;

console.log(‘hi’);

function sendJSON(){

console.log(‘sendJSON’);

// Creating a XHR object

let xhr = new XMLHttpRequest();

// open a connection

xhr.open(“POST”, OrgURL, true);

// Set the request header i.e. which type of content you are sending

xhr.setRequestHeader(“Content-Type”, “application/json”);

// Create a state change callback

xhr.onreadystatechange = function () {

if (status === 0 || (200 <= status && status < 400))

    {

// Print received data from server

result.innerHTML = this.responseText;

console.log(xhr.responseText);

    } else {

// Oh no! There has been an error with the request!

    }

}; 

}

sendJSON();

================

I am expecting to get some kind of JSON object but nothing is showing.

How do I request for JSON content?

Thanks in advance!

Please note there is a url but due to forum rules, i cannot show it.

This is rather outdated way of sending such request, consider using browser’s Fetch API:

Also if you want to request something from the server, GET would be more appropriate method to do so

Thanks for the info!

I will look up on Fetch()!

Hi,
sendJson() will nothing showing because the ajax call is works asyncronously.
Change your function to assyncron function and will work well.