0

I want to do something with the data I store in my var searchedUsers, the problem is that when I do the alert(searchedUsers); there is nothing in it. If I do the alert(searchedUsers); under the var user code. There is something in it.

I assume this is because the code already runs before it is fully executed. Now I guess have to add another callback function in there somewhere only it doesn't seem to work I always get errors.

function addFriend() {
    var formData = "name=" + $("#nameForm").val() + "&familyname="
            + $("#familyname").val() + "&emailaddress="
            + $("#emailaddress").val();
    var searchedUsers = [];
    $.ajax({
        type : "POST",
        url : "ControllerJavascript?action=addFriend",
        dataType : "xml",
        data : formData,
        success : function(xml) {
            $(xml).find("user").each(
                    function() {
                        var user = $(this).find("name").text().trim() + " "
                                + $(this).find("familyname").text().trim()
                                + " // " + $(this).find("email").text().trim();
                        searchedUsers.push(user);
                    });

        },
        error : function() {
            alert("An error occurred while processing XML file.");
        }
    });
    alert(searchedUsers);
    getFriends();
}

Is it possible to add another callback function so first all users are pushed to searchedUsers?

  • 5
    you should put the alert(searchedUsers); right after the .each method – ius May 15 '15 at 11:48
  • 1
    [Related](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call), arguably duplicate – James Thorpe May 15 '15 at 11:49

1 Answers1

1

You already have this function:

success : function(xml) {
...
},

This is your callback. Just call alert after your each method:

success : function(xml) {
        $(xml).find("user").each(
                function() {
                    var user = $(this).find("name").text().trim() + " "
                            + $(this).find("familyname").text().trim()
                            + " // " + $(this).find("email").text().trim();
                    searchedUsers.push(user);
         });
         alert(searchedUsers);
    },
ImreNagy
  • 511
  • 2
  • 10