javascript ajax post json code example

Example 1: send json post ajax javascript

$.ajax({
    url: 'users.php',
    dataType: 'json',
    type: 'post',
    contentType: 'application/json',
    data: JSON.stringify( { "first-name": $('#first-name').val(), "last-name": $('#last-name').val() } ),
    processData: false,
    success: function( data, textStatus, jQxhr ){
        $('#response pre').html( JSON.stringify( data ) );
    },
    error: function( jqXhr, textStatus, errorThrown ){
        console.log( errorThrown );
    }
});

Example 2: ajax data post call in javascript

$.ajax({
   url: 'ajaxfile.php',
   type: 'post',
   data: {name:'yogesh',salary: 35000,email: '[email protected]'},
   success: function(response){

   }
});

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); });