xml request javascript code example

Example 1: xml http request

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

Example 2: Working with XML in JavaScript

/*
    This code comes from Vincent Lab
    And it has a video version linked here: https://www.youtube.com/watch?v=5YQXVgNZvRk
*/

// Import dependencies
const fs = require("fs");
const { parseString, Builder } = require("xml2js");

// Load the XML
const xml = fs.readFileSync("data.xml").toString();
parseString(xml, function (err, data) {

    // Show the XML
    console.log(data);

    // Modify the XML
    data.people.person[0].$.id = 2;

    // Saved the XML
    const builder = new Builder();
    const xml = builder.buildObject(data);
    fs.writeFileSync("data.xml", xml, function (err, file) {
        if (err) throw err;
        console.log("Saved!");
    });

});

Example 3: javascript http request

// Use these functions:

function _GET_REQUEST(url, response) {
  var xhttp;
  if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
  } else {
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      response(this.responseText);
    }
  };

  xhttp.open("GET", url, true);
  xhttp.send();
}

function _POST_REQUEST(url, params, response) {
  var xhttp;
  if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
  } else {
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      response(this.responseText);
    }
  };

  xhttp.open("POST", url, true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send(params);
}


// Use like:
_GET_REQUEST('http://url.com', (response) => {
	// Do something with variable response
  	console.log(response);
});
_POST_REQUEST('http://url.com', 'parameter=sometext', (response) => {
	// Do something with variable response
  	console.log(response);
});