Send JSON object as data in Ajax POST/ GET call

Send JSON object as data in Ajax call.

Suppose you have  a JSON object associated with a variable say json  in our case, you can send this json value as data in the ajax call as follows.

var json = [{'id':1,'name':'user1'},{'id':2,'name':'user2'},{'id':3,'name':'user3'},{'id':4,'name':'user4'}]

function demo(url){
    $.ajax({
        method : 'POST',
        url : url,
        dataType: 'json',
        data : { objects :JSON.stringify(json)},
        success : function(data){
            console.log(data);
        },
        error : function(error){
            alert('OOps Something went wrong, please contact admin');
        }
    });
}
JSON.stringify() method will parse the json object and convert it to a string format that can be sent as data in the Ajax call.

you can also send other data with the json as follows
var json = [{'id':1,'name':'user1'},{'id':2,'name':'user2'},{'id':3,'name':'user3'},{'id':4,'name':'user4'}]

function demo(url){
    $.ajax({
        method : 'POST',
        url : url,
        dataType: 'json',
        data : { 'objects' :JSON.stringify(json), 'otherData' : 'value'},
        success : function(data){
            console.log(data);
        },
        error : function(error){
            alert('OOps Something went wrong, please contact admin');
        }
    });
}

No comments :

Post a Comment