简体   繁体   中英

Array remains empty AJAX/JS/PHP

My php script returns a response in json:

echo json_encode(array(
    "Subject"=>$row['Subject'],
    "date"=>$row['Date'],
    "Sender"=>$row['username'],
    "sender_id"=>$row['user_id'],
    "Message"=>$row['Message'])
);

In JS the single columns should be pushed into the different arrays to later use for a table, but they remain empty

I think the issue has to do with async but I don't know how to do it.

This is the JS code.

var id =45678;

 var names = [];
    var subjects = [];
    var dates = [];
    var messages = [];
    var sender_ids = [];

function getData() {

    return $.ajax({
     type: "post",
     url: '',
     data: {user: id},
     dataType: 'json',
     success: function(response){

        $.each(response, function(i, row) {

         names.push(response.Sender);
         subjects.push(response.Subject);
         dates.push(response.date);
         sender_ids.push(response.sender_id);
        })
     }
    });
  }

$(document).ready( function() {

    getData().done(function (response) {

        if(response.Sender != null) {

            for (var i in response.Sender){
                names.push(response.Sender[i]);

                alert(names); 
            }
        }
        alert(names);
    });

});

The problem is that you return the ajax variable which is wrong the return statement must be inside the success function and one in complete function so that you have a fallback. The .done part is not having a (response) parameter unfortunately. Either you are going to do all your work in success function or you will return everything from there.

var id =45678;

function getData(obj) {

    return ({
     type: "post",
     url: '',
     data: {user: id},
     dataType: 'json',
     success: function(response){
        obj.names.push(response.Sender);
        obj.subjects.push(response.Subject);
        obj.dates.push(response.date);
        obj.messages.push(response.Message);
        obj.sender_ids.push(response.sender_id);
        return obj;
     },
     complete: function(){
       return obj;
     }
    });
  }

$(document).ready( function() {
    var obj = {}
    obj.names = [];
    obj.subjects = [];
    obj.dates = [];
    obj.messages = [];
    obj.sender_ids = [];

    obj = getData(obj);

});

Try this. I wish this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM