javascript request code example

Example 1: 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);
});

Example 2: http request javascript

function httpGetAsync(url, callback) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", url, true); // true for asynchronous 
  xmlHttp.send(null);
}

Example 3: request api

REQUEST :(request url,http methods,header,query param, param,body,cookie)

1-)Request Url where we have Endpoint (domain:Port/Endpoints)

2-)HTTP METHODS(Get, Post, Put, Patch, Delete, Header)

Get: For to retrieve resources from the server
Post: to send or add resource to the server
Put: For update the resources in the server
Patch: For partial update the resource
Delete: For deleting the resource in the server
Head: To get header from the response not the body

3-)HEADER is metadata is about the request,
basically providing more information along
with the request.

-Content Type header : to specify what kind of
 data we are sending to the server
-Accept Header : to specify what kind of data 
 format you want to get in the response like (json or xml)
-Authorization header : used to provide the
 Bearer token in many api's.

4-)Query Parameter: A key value pair usually
 for filtering result

5-)Parameter: for identifying single resource
 among the list of resources.
6-)Payload(BODY): for POST,PUT,PATCH request
(json,xml,plainText,URL encoded for data)
7-)Cookie