SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    UK
    Posts
    163
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    confusion with timings and JSON..Please help!

    What I'm trying to do sounds simple. I want to load various chunks of data into javascript via json and then use it in other functions (such as jquery autocomplete).
    I just can't figure out how to delay the 'other functions' until the data is loaded.
    eg
    Code:
    $(document).ready(function(){
    townarray = getTownArray();
    alert("towns="+townarray);
    }
    function getTownArray() {
    	var myarray = [];
    	var url = "ajaxjson.php?gettownlist=1"; // get town data
    	$.getJSON(url,function(data) {
    		$.each(data, function(key,value) {
    			myarray.push(value['description']);
    		});
    	});
    	return(myarray);
    };
    The alert shows townarray is empty.
    If I wrap the alert in a window.setTimeout, it is fine.

    I've been going round in circles trying to delay the alert until the townarray is filled in. I've tried adding a callback to getTownArray, but it just wouldn't wait for the array to be filled in - is that the way to go?
    Can anyone help please?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,189
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Ajax requests by default run asynchronously which means the code does wait for the Ajax request to complete, to get around this we can simply use jQuery's ajax method instead which has a setting to disable asynchronous connections and make them synchronous which means the code will only execute once the Ajax request is complete. See the below example:

    Code JavaScript:
    function getTownArray() {
        var myarray = [];
     
        $.ajax({
            async    : false,
            dataType : 'json',
            url      : 'ajaxjson.php?gettownlist=1'
        }).success(function(data) {
            $.each(data, function(k, v) {
                myarray.push(v['description']);
            });
        });
     
        return myarray;
    }

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2008
    Location
    UK
    Posts
    163
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect, thank you!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •