daniel__
daniel__

Reputation: 11845

Accessing Ajax Response Data

I have this code that works well:

{"livre":"empty_name"}

    $.ajax({
        url: "sent.php",
        type: "post",
        dataType: "json",
        data: formdata,
        success: function (data) {
            switch (data.livre) {
                  case 'empty_name':

                  break;
        }
    });

but when i try this code (i need the id), the case "empty name" didn't works. The option selected will be the default case:

{"id":"","livre":"empty_name"}

    $.ajax({
        url: "sent.php",
        type: "post",
        dataType: "json",
        data: formdata,
        success: function (id, data) {
            switch (data.livre) {
                 case 'empty_name':

                 break;
        }
    });

Why? and how can be solved? thanks

Upvotes: 3

Views: 27359

Answers (2)

Quintin Robinson
Quintin Robinson

Reputation: 82335

You just need to understand how the data is being returned. In this case data is the object containing all the fields. Your success callback would continue to look like success: function(data) the code you need to change is in the method block itself.

$.ajax({
    url: "sent.php",
    type: "post",
    dataType: "json",
    data: formdata,
    success: function (data) {
        var id = data.id; //ID lives in data.
        switch (data.livre) {
    }
});

Since you redefined the function, the switch will fail because in the example posted livre will reside in the id object and not in the data object.

Upvotes: 2

dontGoPlastic
dontGoPlastic

Reputation: 1782

If I understand correctly with the object up top being the JSON response, I think you want this...

{"id":"","livre":"empty_name"}

$.ajax({
    url: "sent.php",
    type: "post",
    dataType: "json",
    data: formdata,
    success: function (data) {
        var jsonId = data.id;
    }
});

The data parameter of the success callback contains your response (in this case, JSON data). You access your JSON content there.

Upvotes: 5

Related Questions