Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 552
daniel__ Avatar asked Aug 10 '26 12:08

daniel__


2 Answers

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.

like image 174
dontGoPlastic Avatar answered Aug 12 '26 09:08

dontGoPlastic


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.

like image 27
Quintin Robinson Avatar answered Aug 12 '26 08:08

Quintin Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!