In the previous chapter we looked at how PHP can be used to retrieve data from a database and display it in a web browser. In the previous task we called the PHP file directly,however we can also call a PHP script from within a Javascript function. The advantage in doing this is that we can draw fresh results into a webpage without reloading the whole page (for example when a button is clicked or a dropdown menu is changed). In order to do this we need to use something called an AJAX request.
AJAX is a client side technique which allows data to
be sent and retrieved from a server asynchronously, that is, without interfering with the current webpage (i.e. it runs in the background).
An AJAX request can be embedded in a JavaScript function to either send data to a database or
retrieve data from a database, without having to reload the page. Consider the AJAX request code below. Here the fetchData()
function is called (this could be from a button, on page load, from another function etc.) whereafter a getJSON()
function is called that returns JSON encoded data from the server using a
HTTP GET request. Note that
the getJSON()
function is built into a variable '$
' – we'll come back to that shortly.
function fetchData() {
$.getJSON("fetchData.php", function(results) {
document.getElementById('textWrap').innerHTML = results;
});
}
The getJSON()
function accepts two arguments: a string containing
a URL to which the request is sent and a callback function which is executed if the request
succeeds. For the first argument, in this
case we are passing in the fetchData.php file which was created in the previous task, remember that this returns an array of results.
This file will be called, and return the data as before, but instead of writing the reults to the page, the results are
returned to the callback function. The callback function accepts the output of the PHP file as an argument (results
).
If the request is successful the callback function will execute, writing the results into a div called 'textWrap
in the web browser. Note how we are using the Document Object Model (document.getElementbyID) to identify the textWrap div within
our HTML file (the div is empty until the function completes).
The getJSON()
function is actually part of a library called
jQuery. This is a popular library for adding all sorts of JavaScript functionality.
jQuery creates the '$
' variable, and much of its functionality is accessed through
that variable, as here. Although you can make your own AJAX requests
without it, functions like getJSON()
, which wrap around the AJAX request, and parse the results and
present them nicely as JavaScript objects, are much simplier to use.
In order to use an AJAX request such as this one, a link to the jQuery library must be included in the HTML header (exactly as we linked the Google Maps library) alongside the link to our Javascript file which contains the above function:
<script language="javascript" type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script language="javascript" type="text/javascript" src=" script.js">
</script>
As mentioned previously, the advantage of using an AJAX function like this is there is the opportunity to add user interactivity
to webpages. For example the fetchData()
function may be called when the user selects an option from a drop
down menu or when the user clicks a button:
<body>
<div class = "wrapper">
<button onclick = 'fetchData()'>Fetch Data</button>
<div id = 'textWrap'></div>
</div>
</body>
The result set returned from the PHP file is currently text rows, which isn't very useful to us. To do any further processing of the results, we could do with placing the returned data into an associative array first, so that each value can be referenced based on its original column name. An associative array (also known as a map, dictionary or symbol table) is a collection of unique key-value pairs, where each combination of key and value appears only once in the collection. Values can be extracted from an array through reference to their key just as values in a numeric array can be extracted based on their location in the array. For example we could loop through an associative array and retrieve only the latitude and longitude values if we wanted to map each point. We have already seen associative arrays in the form of JSON objects in block one.
Having structured the data as an associative array, we can then send it out as JSON, remembering that this format is all about linked labels and data, making it perfect for associative arrays. Here's how a single associative array would be set up in PHP. Ultimately you want an array of these arrays to hold all the data:
$array = array('id' => 1, 'body' => 'hello world');
echo $array['id'];
echo $array['body'];
PHP Output:
int(1)
string(11) 'hello world'
An associative array in PHP is actually known as an 'ordered map'.
The keys in our dataset will be id
, body
, lat
, and lon
.
In Javascript an associative array is known as an array of JavaScript objects. In Task 4 we will create an associative
array in PHP using the results set returned from the pg_query()
function; this array will form the basis
of what is sent as the result of the AJAX call. Within the JavaScript, the results array only exists as long as
the AJAX callback function is running; therefore the data needs to be
written into a permanent array which will exist outside of the scope of the function.
In order to do this, we need to add a little more code to both our PHP file and JS file.