Sefam
Sefam

Reputation: 1773

Copying an array from a jQuery ajax call

I'm trying to copy a JSON array in this Javascript function:

var test = new array();
function showUser(user, pass, remember)
{
    $.getJSON("login.php", { username : user, password : pass, check : remember }, function(data){  
    for (var i = 0; i<data.length; i++)
    {
        alert(data[i]);
        test[i] = data[i];
    }
    });
    alert(test[0]);
}

Here is the PHP file it links to;

<?php
$arr = array("test1", "test2", "test3");

echo json_encode($arr);
?> 

The problem is that I need to run through the function twice so that my test array contains something, otherwise it remains undefined. How do I fix this?

Upvotes: 1

Views: 601

Answers (2)

lonesomeday
lonesomeday

Reputation: 237965

The easy way to copy an array is with slice:

test = data.slice(0);

Upvotes: 1

Jasper
Jasper

Reputation: 76003

var test = new array();
function showUser(user, pass, remember)
{
    $.getJSON("login.php", { username : user, password : pass, check : remember }, function(data){  
        for (i in data)
        {
            test[i] = data[i];
        }
        alert(test[0]);
    });
}

As Šime Vidas stated, your alert was outside the callback function so it was being called before the data was returned via your AJAX call. That is why the second click on your button alerted what you expected, because it existed after the callback function ran.

Although, rather than loop through the data variable, why not just set test to the value of data:

test = data;

Upvotes: 3

Related Questions