Get JSON data using javascript

Kindly guide me with the code(function) for fetching json data through REST API. POST method and displaying same…Thanks to all

What code do you have so far, and what do you already know about JavaScript?

Thanks I was interested in using xmlhttprequest to initiate REST API after a button with specific id linked to contact form in wordpress is pressed.I have knowledge of javascript but can’t figure out for xmlhttprequest as not much worked with same

Like I wanted to use something like

function UserAction() {
    var xhttp = new XMLHttpRequest();"POST", "Your Rest URL Here", false);
    xhttp.setRequestHeader("Content-type", "application/json");
    var response = JSON.parse(xhttp.responseText);

Kindly guide me how to link the button with this and any changes needs to be done ,as URL will contain my API endpoint-key id and password ,so any particular format?


The problem is in dealing with the response from the server.

Instead of this:

var response = JSON.parse(xhttp.responseText);

You’d need to do something like this:

xhttp.onreadystatechange = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; // status 200 is a successful return.

  if (xhttp.readyState === DONE) {
    if (xhttp.status === OK) 
      var response = JSON.parse(xhttp.responseText);
    } else {
      console.log('Error: ' + xhttp.status); 

This might help:

1 Like

Thanks sorry couldn’t reply,can you please guide on following points.

  1. How to link a button with button id with this javascript call,I want to initiate javascript call based on the button pressed action.I have a button with button id
    2)How to pass REST API url and specify the method like POST


No worries :slight_smile:

const myButton = document.getElementByID(selector);
myButton.addEventListener(() => {
  // Do Ajax here
}, false);"POST", "your-url-here", true);

Thanks kindly let me know the button id in my case button1 should it be like this getElementByID(#button1);?also just to confirm the xhttp url can be placed over the AJAX location //Ajax here?How will I pass the API key and password in the URL what is the format to use ?


Assuming your butting has the ID of button1, then the line should read

const myButton = document.getElementByID("button1");

If it doesn’t have that as an ID, then change it to whatever you’ve named it.

Thanks and kindly tell the xhttp url should be placed at AJAX location / / mentioned in code above?How will I pass the API key and password in the URL what is the format to use

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.