This is a basic technique for using AJAX to load some JSON data from your backend server. This example assumes you are going to use jQuery. Let’s use an example of a refresh button and some time based data. This means you have a UI that has a refresh button and you want to get the latest set of data from your backend. You might have a button on your UI similar to this:

...
<button id="data-refresh-btn" type="button">Refresh</button>
...

First thing you want to do is attach on onclick event and have a function that will contain your AJAX code. Similar to this in your Javascript file.

$('#data-refresh-btn').onclick = function () {

}

Now let’s add some AJAX. You’ll notice the URL that i’m using is passing the current date as a GET parameter to the page. I’m passing the date in millis because it will be easier to load that into a date object on the server side since pretty much any language has a constructor for that. There are ways to pass in a whole json payload as part of the request but that is beyond the scope of this example.

$('#data-refresh-btn').onclick = function () {
   $.ajax({
      url: 'http://<yourdomain>/datasource.php?date=' + new Date().getMilliseconds(),
      success: function(data) {
            //user your new data here.
      },
      type: 'GET'
    });
}

Since your data is going to be JSON formatted, the javascript engine can use it as if it were a regular object. You can access your data using dot notation.

Next up we need to have our data return properly from the server. I’m going to use PHP for this example but you can use anything that will return HTML to the browser.

<script type="application/json">
<?php
    $date = $_GET["date"];
    // get your new data and store it as a json string in $json
    echo $json;
?>
</script>

That’s the entire page. There’s no need to have a

<html>

or

<body>

tags. It’s very important that the object that you end up printing is a valid JSON string.

And you’re done!

Leave a Reply

Your email address will not be published. Required fields are marked *