Sei sulla pagina 1di 6

ajax - mysql database

We already know how to run an external PHP script with AJAX, so let's take it to the next level and pull some data down from a MySQL database. Our "order.html" file and PHP script will have to be updated and we also need to make a new database.

create the mysql table


To clearly illustrate how easy it is to access information from a database using Ajax, we are going to build MySQL queries on the fly and display the results on "order.html".
Create a new database or use an existing one and then import the tableajax_example.sql to

that database. This sql file will create the table ajax_exampleand insert all the data rows. The table has four columns:

ae_name - The name of the person ae_age - Person's age ae_sex - The gender of the person ae_wpm - The words per minute that person can type

update order.html
We want to be able to build queries from our HTML file, so there are a few form elements that will need to be added. The three inputs we are going to implement are:

Maximum Age (Text Input) - Let the user select the maximum age to be returned. Maximum WPM (Text Input) - Let the user select the maximum wpm to returned. Gender (Select Input) - Let the user select the gender of a valid person.

order.html HTML/Javascript Code:


<html> <body> <script language="javascript" type="text/javascript"> <!-//Browser Support Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false;

} } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ document.myForm.time.value = ajaxRequest.responseText; } } var age = document.getElementById('age').value; var wpm = document.getElementById('wpm').value; var sex = document.getElementById('sex').value; var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex; ajaxRequest.open("GET", "ajax-example.php" + queryString, true); ajaxRequest.send(null); } //--> </script>

<form name='myForm'> Max Age: <input type='text' id='age' /> <br /> Max WPM: <input type='text' id='wpm' /> <br /> Sex: <select id='sex'> <option>m</option> <option>f</option> </select> <input type='button' onclick='ajaxFunction()' value='Query MySQL' /> </form> </body> </html>

If the new Javascript code is foreign to you, be sure to check out our lesson on Javascript's getElementById Function. With our new Javascript code var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex; we have built a query string to pass along the information from our HTML form to our PHP script.

ajax - passing variables via query string


A query string is a way of passing information by appending data onto the URL. You may have often seen it on the web, it's all the information that appears after a question mark "?". When you submit a form using GET it builds a query string, all we're doing here is manually building our own.

http://www.tizag.com/somescript.php?variable1=value1&variable2=value2

The left side of the equals operator is the variable name and the right side is the variable's value. Also, each variable is separated with an ampersand &.

For example, if we wanted to send the variables age, sex, and wpm with values 20, f, 40 to our PHP script ajax-example.php then our URL would look like:

http://www.tizag.com/ajax-example.php?age=20&sex=f&wpm=40

Now we need to build a new PHP script to take these variables and run a MySQL query for us.

ajax - create ajax-example.php script


We already changed the destination URL in our ajaxRequest.open method, now we need to make a script to grab those variables from the query string and execute a MySQL Query. We're also going to use a special functionmysql_real_escape_string to prevent any harmful user input from doing something they aren't supposed to (we're going to take steps against SQL Injection).

ajax-example.php Code:
<?php $dbhost = "localhost"; $dbuser = "dbusername"; $dbpass = "dbpassword"; $dbname = "dbname"; //Connect to MySQL Server mysql_connect($dbhost, $dbuser, $dbpass); //Select Database mysql_select_db($dbname) or die(mysql_error()); // Retrieve data from Query String $age = $_GET['age']; $sex = $_GET['sex']; $wpm = $_GET['wpm']; // Escape User Input to help prevent SQL Injection $age = mysql_real_escape_string($age); $sex = mysql_real_escape_string($sex); $wpm = mysql_real_escape_string($wpm); //build query $query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'"; if(is_numeric($age)) $query .= " AND ae_age <= $age"; if(is_numeric($wpm)) $query .= " AND ae_wpm <= $wpm"; //Execute query $qry_result = mysql_query($query) or die(mysql_error()); //Build Result String $display_string = "<table>"; $display_string .= "<tr>"; $display_string .= "<th>Name</th>"; $display_string .= "<th>Age</th>"; $display_string .= "<th>Sex</th>"; $display_string .= "<th>WPM</th>"; $display_string .= "</tr>"; // Insert a new row in the table for each person returned while($row = mysql_fetch_array($qry_result)){ $display_string .= "<tr>"; $display_string .= "<td>$row[ae_name]</td>"; $display_string .= "<td>$row[ae_age]</td>"; $display_string .= "<td>$row[ae_sex]</td>";

$display_string .= "<td>$row[ae_wpm]</td>"; $display_string .= "</tr>"; } echo "Query: " . $query . "<br />"; $display_string .= "</table>"; echo $display_string; ?>

the next step - updating order.html


We have completed our initial order.html and ajax-example.php setup, now we just need our order.html page to update correctly when a query is returned. We'll be using a couple advanced Javascript functions to update a segment of order.html with the MySQL result display_string.

ajax - javascript techniques


The real trick of Ajax is updating a segment of the page without actually having to reload the entire page. This little trick is often done by utilizing a Javascript property known as innerHTML. Each HTML element on a page has aninnerHTML associated with it that can be changed at any time. For us, we need to update it when our ajax-example.php script has finished executing.

updating the order.html page


First we need to create a new div on this page that will contain the results of the query. After we have that in place we can update the div's innerHTML with the information returned by ajax-example.php. Remember that this result is stored inside ajaxRequest.responseText.

order.html HTML/Javascript Code:


<html> <body> <script language="javascript" type="text/javascript"> <!-//Browser Support Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false;

} } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } var age = document.getElementById('age').value; var wpm = document.getElementById('wpm').value; var sex = document.getElementById('sex').value; var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex; ajaxRequest.open("GET", "ajax-example.php" + queryString, true); ajaxRequest.send(null); } //--> </script>

<form name='myForm'> Max Age: <input type='text' id='age' /> <br /> Max WPM: <input type='text' id='wpm' /> <br /> Sex: <select id='sex'> <option value='m'>m</option> <option value='f'>f</option> </select> <input type='button' onclick='ajaxFunction()' value='Query MySQL' /> </form> <div id='ajaxDiv'>Your result will display here</div> </body> </html>

quick ajax recap


So far we have created a new MySQL table, written a new PHP script and updated order.html twice. If you have followed the directions in the Ajax MySQL lesson and created the MySQL table ajax_example and ajax-example.php script then the updated order.html page will function like our example below.

Display:
Max Age: Max WPM: Sex: Your result will display here

ajax javascript lessons


If you want to update a non form element, be sure to use the innerHTMLattribute that is associated with all HTML elements. In our case we are updating adiv every time a query is

sent off. Also, remember that you can easily access an HTML element by giving it an id and using Javascript's document.getElementByIdfunction. If you have successfully completed this advanced Ajax lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.

Potrebbero piacerti anche