3

I'm currently writing a web application that requires some data from the server to be stored in a Javascript object. The amount of data that needs to be loaded is very small, probably around 1 KB. I'm faced with the decision of how to load the data into the application. Here are the two obvious (to me anyway) paths I could take:

1 - Using jQuery's document-ready function, I make an AJAX request to the server and store the response in the appropriate Javascript object. It might look something like this.

$(function() {
    $.get('index.php?get=data', function(data) {
        myObj.addData(data);
    });
});

2 - The alternative would be to send the data along with the page during the initial page request. In order to do that, I would have my server generate the data and output it in the markup between <script> tags. Since my current project is in PHP, it would look something like this:

...
</div>
<script>
    window.myData = <?= json_encode($myData) ?>;
</script>
...

The jQuery document-ready function would later look for the global variable called window.myData and load it into the appropriate Javascript object like this:

$(function() {
    myObj.addData(window.myData);
});

Is there a preferred way of loading data into Javascript objects? Although the amount of data being stored is relatively small, the AJAX call could result in a longer wait if the server's ping isn't great. However, it would seem that AJAX calls are more popular when it comes to these things. Is there a valid reason?


EDIT: The data would very rarely be changed (maybe once a year). Therefore, browser caching should not be much of an issue.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
James Hall
  • 300
  • 3
  • 10
  • @ShivanRaptor No, I believe `json_encode` is the correct function. Note that `$myData` is an associative array in PHP that should be converted to an array in Javascript. Therefore, encoding it into JSON will provide the correct syntax that Javascript will understand. – James Hall Jul 26 '13 at 02:47
  • I prefer option 1:window.myData = = json_encode($myData) ?>; Mainly as you have the data on load rather then getting the data after on load. But that's if the data, is like you say, small. – deach Jul 26 '13 at 03:00
  • json_encode is typically used server side to encode the request data into javascript object notation. jQuery will handle the decode after the request. json_decode will turn a json object into a php array which cannot be used directly by javascript without manually parsing it. – Hobbes Jul 26 '13 at 03:05

1 Answers1

2

use the $.getJSON method:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});

OR could use the $.each() function to loop through the data:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});
liyakat
  • 11,825
  • 2
  • 40
  • 46
  • Could you elaborate a bit about why this method is the better choice? I don't see any advantage to loading the data in a separate request. – James Hall Jul 26 '13 at 02:53
  • or if you are using jQuery.parseJSON - new in jQuery 1.4.1 so refer http://api.jquery.com/jQuery.parseJSON/ – liyakat Jul 26 '13 at 02:56
  • I'm still unclear about why this is the way to do it. I know that option is there, but I would like to know **why** it is the better option, or **why** it is not. – James Hall Jul 26 '13 at 03:01
  • 1
    This is the preferred method. Personally I load the data as raw text than use jQuery.parseJSON(response) after the request. I only do this because on occasion i do actually want the raw text of a response. How you manage what data is pulled per request is up to you, but this is how to handle the response as a javascript object. JSON = JavaScript Object Notation. – Hobbes Jul 26 '13 at 03:02
  • @Hobbes, thanks for the input. Would you say this just a matter of convention? – James Hall Jul 26 '13 at 03:08
  • Convention and ease of use. Once you get used to using json, you will wonder how you ever used ajax without it. Basically it converts php arrays/objects into javascript. Very convenient. – Hobbes Jul 26 '13 at 03:10