Accessing Ajax Response Data

This code works well for me:

{"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 to execute this code (i need an id) the "empty name" case doesn't work. The selected option will be used by default:

{"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 you decide? thank

+3


source to share


2 answers


If I understand correctly that the object at the top is a JSON response, I think you need this ...

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

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

      



The data

callback parameter success

contains your response (in this case, JSON data). You are accessing your JSON content.

+3


source


You just need to understand how the data is returned. In this case data

, it is an object containing all fields. Your success callback will still look like the success: function(data)

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) {
    }
});

      



Because you have overridden this function, the switch will fail, because in the example placed livre

it will be in an object id

, not an object data

.

+1


source







All Articles