ajax post with data 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: jquery post json example

<script type="text/javascript">
    function send() {
        var person = {
            name: $("#id-name").val(),
            address:$("#id-address").val(),
            phone:$("#id-phone").val()
        }

        $('#target').html('sending..');

        $.ajax({
            url: '/test/PersonSubmit',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                $('#target').html(data.msg);
            },
            data: JSON.stringify(person)
        });
    }
</script>

Example 3: 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 4: jquery ajax $.post with data

$.post('http://example.com/form.php', {category:'client', type:'premium'}, function(response){ 
      alert("success");
      $("#mypar").html(response.amount);
});

Example 5: js ajax post strings

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});