0

Okay so after searching Stack Overflow for answers I found two threads and tried them both but they did not work for me.

Assign data from jQuery getJSON to array

How to get JSON array from file with getJSON?

My issues is I want to work with some data from a database for a mapping utility, however some elements of the JSON dissappear after you call the Jquery method $.getJSON(). I can create them to a 'ul' element just fine. I CANNOT get them to push to an array of array's with any method I have tried yet. I am asking here as I am curious what I am doing wrong. I have thought I may have to traverse the DOM to get the elements once populated maybe but that seems silly to me and I was wondering if there was an easier way potentially. I am a novice at javascript and Jquery but understand programming concepts.

The concepts I am using are this:

  1. I have a SQL Server 2008 database with values:

    PlaceID PlaceName
    1       Place 1
    2       Place 2
    3       Place 3
    4       Place 4
    
  2. I can create a PHP script with the 'sqlsrv' driver to get the values and output a

    echo json_encode($data);
    
  3. I can confirm I can return the data from this PHP script in IIS locally. (with all the special jerry rigging you have to do to IIS to make it like PHP)

  4. I can call the php script and display it's data with JQuery library 2.0.3.js using the

    $.getJSON('SqlTalk.php')
    
  5. I can populate elements in the HTML with this, but I cannot get an array of array's for reuse with other objects, which is what I really really want. Ultimately I want to make an entire javascript that just gets an array of arrays from the PHP script and then reference that javascript either embedded or as a reference to use for mapping. However it appears $.getJSON is asychrnonous from my reading but even the methods I am seeing are not working for me to attempt to 'push' to an existing array. It may be that I am misunderstanding syntax when mixing Jquery and traditional javascript as well though.

Complete HTML code where the bottleneck is. Basically PHP will be returning data as shown in step 1 except as a JSON object. This is a simple example to get me beyond proof of concept first. I can push explicitly to the array, and I can generate the child items of the ul element just fine. I cannot push the items from 'getJSON' at all no matter what I attempt at reformating the getJSON method from what I have read.

<html>
<head>
        <script type='text/javascript' src='JQuery 2.0.3.js'></script>
</head>
<body>
    <ul></ul>
    <script>
        test = [
                {
                  PlaceID: "1",
                  PlaceName: "Somewhere"
                }
               ]

        test.push({PlaceID: "2", PlaceName: "SomewhereElse"});

        function getArray() {
            return $.getJSON('SqlTalk.php')
        }

        getArray().done(function(json){
           $.each(json, function(key, val){
              //test[key] = { PlaceID: val.PlaceID};  // doesn't work
              test.push({PlaceID: val.PlaceID, PlaceName: val.PlaceName});  // also does not work, can't push.
              $('ul').append('<li id="' + key + '">' + val.PlaceName + '</li>');
           });
        });

        alert(test.length);
        // So I get my output to the 'ul' element fine, but my test array never gets the values.
        //I have tried what others have stated and it does not work.
   </script>

</body>
</html>
3
  • Sorry, you simply can't do that. you're alert is happening long before the ajax request in getArray is complete. Instead, store the jqXHR object returned globally and apply another done to it when you need to get to it's data again. Commented Aug 23, 2013 at 18:54
  • Okay but in essence I only wants something similar to var items = []; $.getJSON('SQLTalk.php', function(data){ $.each(data, function(key, place){test.push({PlaceID: place.PlaceID, PlaceName: val.PlaceName }); }); I DO WANT a global to return, I don't know how to do it or do it in such a way that order of operation is correct. Commented Aug 23, 2013 at 19:22
  • You can update the global all you want, however you won't be able to use it until after the request is complete. Commented Aug 23, 2013 at 19:23

2 Answers 2

2

The global will not be updated until after the request is complete.

    var getArrayPromise = getArray().done(function(json){
       $.each(json, function(key, val){
          //test[key] = { PlaceID: val.PlaceID};  // doesn't work
          test.push({PlaceID: val.PlaceID, PlaceName: val.PlaceName});  // also does not work, can't push.
          $('ul').append('<li id="' + key + '">' + val.PlaceName + '</li>');
       });
    });

    getArrayPromise.done(function(){
        alert(test.length);
    });

there is no workaround, that's just how asynchronous requests work. The clock keeps ticking and the code keeps executing while the request is being received.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh.... interesting. So is what you are saying is I was getting it the whole time, just the order of operation was not showing it due to order of operation of it being asynch? And my being not as skilled in JQuery I just needed a method to ensure the getArray was finished. My last question would be: "Can I just wrap up what you did to return the array in a seperate javascript file to reference by the 'test' name?" You will have to forgive me as I am still pretty novice at Jquery and Javascript and am learning as I go with this project.
Less order of operation, more so the timing. Think of an ajax request as a setTimeout. the code in the "complete" portion of the setTimeout doesn't happen until after the set delay. the same thing is true of ajax requests. Yes you can access test in another js file, however the same rule applies; you'll have to wait until it has been populated.
1

You might want to use the complete callback on the AJAX response

$.ajax({
  url: 'SqlTalk.php',
  dataType: 'json',
  success: function(data){        
    for (var i = 0; i < data.length; i++) {
        test.push({PlaceID: data[i].PlaceID, PlaceName: data[i].PlaceName});
        $('ul').append('<li id="' + i + '">' + data[i].PlaceName + '</li>'); 
    }
  },
  complete: function(){
    console.log(test);
  }
});

I did a quick jsfiddle ( http://jsfiddle.net/Ar7kX/ ) to show the complete callback in action (using another kind of data and way, since I don't have obviously access to your real data :) ), a more proper one with arrays of arrays to follow in minutes (if I know how I can gather foursquare data from a jsfiddle)

EDIT

Here you can see an array of array in action directly pulled from foursquare http://jsfiddle.net/f38F3/1/ (30 items), hope this reflects the same situation you have pulling data from your php script

1 Comment

Thanks works as well thanks. The issue I am now going to get into is I will need to populate a javascript file, or would like to. That dynamically gets a more complex tree structure of values. I would need to know some how when this is done from a base html file.

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.