how to send data in ajax post method code example

Example 1: jquery ajax post example

var formData = {name:"John", surname:"Doe", age:"31"}; //Array 

$.ajax({
    url : "https://example.com/rest/getData", // Url of backend (can be python, php, etc..)
    type: "POST", // data type (can be get, post, put, delete)
    data : formData, // data in json format
  	async : false, // enable or disable async (optional, but suggested as false if you need to populate data afterwards)
    success: function(response, textStatus, jqXHR) {
    	console.log(response);
    },
    error: function (jqXHR, textStatus, errorThrown) {
		console.log(jqXHR);
      	console.log(textStatus);
      	console.log(errorThrown);
    }
});

Example 2: javascript send post data with ajax

function makeRequest (method, url, data) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    if(method=="POST" && data){
        xhr.send(data);
    }else{
        xhr.send();
    }
  });
}

//POST example
var data={"person":"john","balance":1.23};
makeRequest('POST', "https://www.codegrepper.com/endpoint.php?param1=yoyoma",data).then(function(data){
              var results=JSON.parse(data);
});

Example 3: javascript ajax post send an object

function postAjax(url, data, success) {    var params = typeof data == 'string' ? data : Object.keys(data).map(            function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }        ).join('&');
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");    xhr.open('POST', url);    xhr.onreadystatechange = function() {        if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }    };    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');    xhr.send(params);    return xhr;}
// example requestpostAjax('http://foo.bar/', 'p1=1&p2=Hello+World', function(data){ console.log(data); });
// example request with data objectpostAjax('http://foo.bar/', { p1: 1, p2: 'Hello World' }, function(data){ console.log(data); });

Tags:

Php Example