Loading values into DOM with AJAX and PHP

Posted by admin at December 31, 2016

This is just my implementation of AJAX in my projects, warts and all.

Ajax PHP

This is script simply loads values from a MySQL table `tbl_airports`.


<?php
    // build the read query
    $sql = 'SELECT * FROM `tbl_airports` WHERE 1';

    // submit the query to generate rows
    $rs = mysql_query($sql, $conn) or die(mysql_error());

    // fetch the first row
    $row = mysql_fetch_assoc($rs);

    // calculate total rows
    $total_rows = mysql_num_rows($rs);

    // initialise the html result
    $html = '';

    for ($i=0; $i<$total_rows; $i++)
    {
        // append the row 
        $html .= '<tr valign="top">'
                .'<td>'.($i+1).'</td>'
                .'<td>'.$row['airport_code'].'</td>'
                .'<td>'.$row['airport_iata_code'].'</td>'
                .'<td>'.utf8_encode($row['airport_desc']).'</td>'
                .'<td>'.utf8_encode($row['airport_city']).'</td>'
                .'<td>'.$row['airport_notes'].'</td>'
            .'</tr>'
        ;

        // load the next row
        $row = mysql_fetch_assoc($rs);

    }

// display the results
echo $html;

?>

Ajax JS

Next, we have to retrieve these values with AJAX. This script will handle asynchronous calls to the ajax.php, retrieve values and send them to the specified HTML element (our global select box). So first we initialise AJAX.


//var xmlhttp;
//var url;

function ajax_function()
{

	if (window.ActiveXObject)
	{
		xml_http = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if (window.XMLHttpRequest)
	{
		xml_http = new XMLHttpRequest();
	}
	else
	{
		alert("You are using an old browser. Please get a newer one.");
	}

	return xml_http;
}

Here is the main function that handles the AJAX calls to the ajax PHP file.


function gen_ajax_opt (action, selval, src, result_div_id, result_value, lgif_id)
{

	// set the default values for the parameters

	// the default value for the action is to display the states
	if (action === undefined) action = 'lopt_states';
	// the selected index for our select box
	if (selval === undefined) selval = '';
	if (src === undefined) src = '';
	// where to paste the AJAX results (in this case our select box)
	if (result_div_id === undefined) result_div_id = 'g_res_box';
	// the result value type HTML, input or select box option 
	if (result_value === undefined) result_value = 'html';
	// the loading icon
	if (lgif_id === undefined) lgif_id = 'lgif_id';

	// get the result element
	var res_div = document.getElementById(result_div_id);

	// get the loading gif
	var lgif = document.getElementById(lgif_id);

	// show the loading gif
	lgif.src = 'img/l.gif';

	// create the xmlhttp
	xml_http = ajax_function();

	// monitor for changes
	function stateChanged ()
	{
		if (xml_http.readyState == 4)
		{
			// display the result in the appropriate div
			switch (result_value)
			{
				case 'val':
				case 'value':
					// the result element is a text box : change the value
					res_div.value = xml_http.responseText;
					break;
				case 'selindex':
					// the result element is a select box : change the selected index
					res_div.options[divTo.selectedIndex].value = xml_http.responseText;
					break;
				default:
					// the html element is a  : the inner html is sent to the result
					res_div.innerHTML = xml_http.responseText;
			}

			// hide the loading gif
			lgif.src = 'img/dot.png';

		}
	}

	// build the url
	url = "inc/ajax.php?lopt=" + action + "&src=" + src + "&sval=" + selval;

	// make the ajax call
	xml_http.onreadystatechange = stateChanged;
	xml_http.open("GET", url, true);
	xml_http.send(null);

}
  • The action parameter is the command that determines the table to list options from,
  • selval defines the selected option in the global select box,
  • result_div_id is the HTML element where the result will be sent to
  • result_value is used to determine the kind of HTML element we are dealing with, for this tutorial, we would be using HTML for innerHTML,
  • lgif_id is the ID of the loading icon. The function toggles the src property of the image to and from a loading icon while the AJAX call is being made. This way the user is notified that values are being retrieved behind the scenes.

For the purpose of this tutorials we will not be using the src parameter but I typically use this parameter to pass special SQL strings for limiting the options generated by inc/ajax.php.

HTML

For the HTML, first we add the loading icon container


<span><img id="lgif_id" name="lgif_id" class="" src="img/dot.png" width="16" /></span>   

Next is the link that initiates the AJAX calls.


<?php $lopt = 'lopt_airports'; ?>
<a href="#" title="click to select value"
    onclick="
        // populate the global select box using AJAX
        gen_ajax_opt('<?php echo $lopt; ?>');
    "
>
    <span class="fw_b">Load Airports</span>
</a>
<br><br>

Then finally, we add the section that will collect the returned values after the calls. Because we are working with tables, we will setup a table template.


<table style="width:100%">
    <thead>
        <tr>
            <td>SN</td>
            <td>CODE</td>
            <td>IATA</td>
            <td>Airport Name</td>
            <td>City</td>
            <td>Country</td>
        </tr>
    </thead>
    <tbody id="g_res_box" name="g_res_box">
    </tbody>
</table>
<br><br>

Putting all together:

You can download the entire application here and see how everything fits. GitHub link is here.

   6 likes

Suggested Read