0

I have problem to return array in jquery. I used ajax to response data from mysql and I have to add it do array and return.

This is my code:

function addOption()
    {
         itemsarray = [];

        $.ajax({
            type: "POST",
            url: "",
            data:{
                option: 'com_zamowienia',
                view: 'zamowienia_lista',
                task: 'getStatusy'
            },
            success: function(data){
                var obj = $.parseJSON(data);         
                    for (x=0; x<obj.length; x++) {
                        itemsarray.push(obj[x].nazwa);
                }
            }
        });

        return itemsarray;
    }

When I use : alert(addOption()). I see empty alert

1
  • By default, AJAX calls are asynchronous. You can not return the results from the function, as it has not happened at the time it finishes. Commented Sep 18, 2012 at 15:54

1 Answer 1

4

As AJAX is asynchronous, so you can't return array like that.

So, you should use callback function to get the array:

function addOption(callback)
    {
         itemsarray = [];

        $.ajax({
            type: "POST",
            url: "",
            data:{
                option: 'com_zamowienia',
                view: 'zamowienia_lista',
                task: 'getStatusy'
            },
            success: function(data){
                var obj = $.parseJSON(data);         
                for (x=0; x<obj.length; x++) {
                        itemsarray.push(obj[x].nazwa);
                }
                // return you itemsarray through callback function parameter
                callback(itemsarray);
            }
        });
    }

Call the function like:

addOption(function(myarr) {
   console.log( myarr );
});
Sign up to request clarification or add additional context in comments.

Comments

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.