Search code examples
jqueryjsonresponse

Read JSON returned by AJAX call


I am new to AJAX. I am submitting my form data into a end point using AJAX. The endpoint is returning a json string with some response data. I tried many things but wasn;t able to read the JSON.

I can parse the JSON. At this point, I want to figure out how I can read the JSON returned by the end point.

My code so that posts to the end pint.

$('.ent-lead-form form').on('submit', function(e){
        e.preventDefault();
        var form = this;

        if($(this).find('.err').length == 0){
            $(this).parent().prepend('<div class="form-mask"></div>');

            $.ajax({
                url: $(this).attr('action'),
                type: 'POST',
                data: $(this).serialize(),
                success: function(data){

                    var data = JSON.parse(json);
                    alert(data);

                    // redirect to success or show thank you
                    if( $(form).find('input[name=successurl]').length == 1 ){
                        window.location = $(form).find('input[name=successurl]').val();
                    } else {
                        $(form).parent().prepend('<div class="confirm-mask">Thank you for your submission.</div>');
                    }

                    // cleanup
                    $('.form-mask').remove();

                },
                error: function(data){
                    // show error
                    $(form).parent().prepend('<div class="confirm-mask">There was an error processing your request.  Please reload the page and try again.</div>');
                    $('.form-mask').remove();

                }
            });


       }
});  

Solution

  • You have an error here ..

     success: function(data){
    
                        var data = JSON.parse(json);
                        alert(data);
    

    Change this to

    success: function(jsondata){
    
                        var data = JSON.parse(jsondata);
                        console.log(data);
    

    Your "data" will be an object. You can get to your values wuith teh dot notation

    data.value
    

    To add a comment to this: It is better to start using .done()

    Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

    http://api.jquery.com/jquery.ajax/