0

Below is my code:

<script src="jquery-1.8.3.js" type="text/javascript">
</script>

<script type="text/javascript">

var obj=[]  ;
    function getData(){
        $.ajax({
            url:'jqueryJsonTest.php',
            type:'POST',
            dataType: 'json',
            cache: true,
            success:function(data){
            obj = data ; 
            alert ("alert 1: "+obj.length);
            }
        });
        }

$(document).ready(function() {
    getData();
    alert("alert 2: "+obj.length);
    alert("alert 3: "+obj.length);
});

</script>

Why is the first result after saving data an empty array?

1 Answer 1

0

You are making an asynchronous AJAX call which returns immediately. It returns before the success callback is executed (where you are setting obj to whats returned). What you should do is do further processing in the success handler - OR - making your ajax call synchronous using async: false option (not recommended)

Try passing the callback handler to your getData() function. i.e. something like:

function getData(mycallback){
    $.ajax({
        url:'jqueryJsonTest.php',
        type:'POST',
        dataType: 'json',
        cache: true,
        success:function(data){
            mycallback(data);
        }
    });
}

$(document).ready(function() {
    getData(function(obj) {
        alert("alert 2: "+obj.length);
        alert("alert 3: "+obj.length);
    });
});
0

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.