software-mariodiana
10/19/2014 - 12:25 AM

Use jQuery to perform an Ajax POST request of a JSON document, getting a JSON document in the response.

Use jQuery to perform an Ajax POST request of a JSON document, getting a JSON document in the response.

// In this example, the server echoes back the JSON from the request.
$(document).ready(function() {

    var stooges = { };
    var stoogesList = [ ];
    stoogesList.push('Larry');
    stoogesList.push('Moe');
    stoogesList.push('Curly');
    stooges.brothers = stoogesList;
    
    // Assume the JSON is submitted when the user presses a button.
    $('#submitButton').click(function() {
        $.ajax({
            url: 'http://localhost:8080/rest/', 
            type: 'POST', 
            contentType: 'application/json', 
            data: JSON.stringify(stooges), 
            dataType: 'json'
        })
        .done(function(data, textStatus, jqXhr) {
            // The JSON must be processed before anything else is done.
            console.log(jqXhr.responseJSON);
            alert("Success");
        })
        .fail(function(jqXhr, textStatus, errorThrown) {
            console.log("Error: " + jqXhr.status + ' ' + errorThrown);
            alert("Error: " + jqXhr.status + ' ' + errorThrown);
        })
        .always(function() {
            console.log('Cleanup.');
        });
        // End Ajax call.
    });
});