Common Ajax Function in Jquery and Javascript to Call Server

Ajax makes your application more flexible, you don’t need to reload or refresh the whole body for small changes, you can made changes in any part without loading page.

var xhr;
function request_call(url,mydata)
{
    if(xhr && xhr.readyState != 4){
        xhr.abort();
    }

    xhr = $.ajax({
        url: url,
        type :'post',
        dataType: 'json',
        data : mydata,
    });
}

Common Ajax function use in jquery click event, change event, blur event etc… and ajax to server call.

$('.AddtoCart').click(function(event){
    event.preventDefault();
    var totaldiscount = $('#totaldiscount').html();
    var totalamount = $('#totalamount').html();
    request_call("demo.php",'totaldiscount='+totaldiscount+'&totalamount='+totalamount);
           xhr.success(function( mydata ) {
            if(mydata.success)
            {
                  
            }
        });
});

Next common ajax function call in blur event in ajax to server call.

$('.Discount').blur(function(event){
    event.preventDefault();
    var totaldiscount = $('#totaldiscount').val();
    request_call("discount.php",'totaldiscount='+totaldiscount);
           xhr.success(function( mydata ) {
            if(mydata.success)
            {
                  
            }
        });
});

Leave a Reply

Your email address will not be published. Required fields are marked *