0

I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
    $.ajax({
        url: 'loaddata.php',
        success: function(data){
            var arr = data.split('|');          
            for(var i=0; i<arr.length; i++){
                var miniArr = arr[i].split(',');
                db.push(miniArr);
            }
            printTest();    //work here         
        }
    });
    printTest();    //not working and collapse here 
});

function printTest(){
    document.getElementById('test').innerHTML += db;
}

</script>
</head>
<body>
<div id="test" />
</body>
</html> `

My php file should be fine,

<?php
$database = file('database');
foreach($database as $item){
    if ($item===end($database))
        echo $item;
    else
        echo $item.'|';
}

?>

Thanks in advance.

2 Answers2

0

Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.

If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • @user2772441 -- Don't do that! There's no guarantee your AJAX call is going to finish in that time, so what if it doesn't? You should handle it in your `success` callback. – tymeJV Sep 12 '13 at 13:00
  • By the javascript httpRequest method I can check condition httpRequest.status == 200. Are there any similar method to make sure the process complete before I go on with the other part of the program? – user2772441 Sep 12 '13 at 13:37
  • This thread should help: http://stackoverflow.com/questions/5344145/how-to-get-response-status-code-from-jquery-ajax @user2772441 – tymeJV Sep 12 '13 at 13:39
-1

You can't call your second printTest() here.

And for the record, try to use JSON to retrieve your datas, it's way much easier.

David
  • 453
  • 3
  • 14