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?

2
  • 5
    you should put the alert(searchedUsers); right after the .each method Commented May 15, 2015 at 11:48
  • 1
    Related, arguably duplicate Commented May 15, 2015 at 11:49

1 Answer 1

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);
    },
Sign up to request clarification or add additional context in comments.

1 Comment

oh ok, off course. I was trying to add a new function(){ }); somewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.