3

I get the following response from the server after doing an ajax request:

{"error":false,"success":true}

My ajax code:

$.ajax({
    url: '/update',
    type: 'post',
    data: $(this).serialize(),
    success: function(response) {
        alert(response)
    },
    error: function() {
        alert('An error occured, form not submitted.');
    }
});

instead of alerting the whole response I want to alert the value of "success", which in this case would be true. How to do this?

Clive
  • 36,918
  • 8
  • 87
  • 113
Linda
  • 143
  • 1
  • 1
  • 4
  • You have to parse the JSON into a JavaScript object: http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – Felix Kling Sep 07 '11 at 18:07

4 Answers4

4

Like so:

alert(response.success);
Naftali
  • 144,921
  • 39
  • 244
  • 303
3
   $.ajax({
        url: '/update',
        type: 'post',
        dataType: 'json', 
        data: $(this).serialize(),
        success: function(response) {

                        alert(response.success)

        },
        error: function() {
            alert('An error occured, form not submitted.');
        }
    });
genesis
  • 50,477
  • 20
  • 96
  • 125
2

Try this:

alert(response.success);
Chandu
  • 81,493
  • 19
  • 133
  • 134
2
alert(response.success);

would do it, you can add dataType: 'json' to your $.ajax options to make absolutely sure it's evaluated as an object in your callback.

Clive
  • 36,918
  • 8
  • 87
  • 113
  • thanks, adding the dataType did it. I called it right before posting he question but the dataType was required for me. – Linda Sep 07 '11 at 18:17