AJAX is very useful for example to get the data we need and display it to the user without refreshing the page. AJAX is basically JavaScript used to interact with data stored on a server. Where exactly in the server? Well, it can be stored in a database such as MySQL or in an XML file. In this tutorial I am going to show you how to use AJAX with MySQL database and then XML. As many of us use libraries I will be using jQuery but will also show you how it is done with pure JavaScript as I think it’s important to understand how it works.
Demo
This is a simple demo showing what we can do with AJAX. When clicking a button AJAX is called in order to get the right data from the server (XML file in this example) and display it without the page being reloaded. I didn’t spend too much time on the layout as the most important here is the result (did a little effort to design nice buttons though).
IMPORTANT NOTE
Before you go further. In this tutorial I am not considering security issues but you definitely should. Always make sure that any value is safe before being sent to the server.
Also, there are deferent ways to use AJAX depending on what you want to achieve. Here I am just trying to give you an idea how it can be used with a very simple example.
HTML
Here are the elements you will need for this tutorial.
<button class="button" onclick="getDataFile(1)">Home</button>
<button class="button" onclick="getDataFile(2)">About</button>
<button class="button" onclick="getDataFile(3)">Contact</button>
<div id="wrap-container">Content will display here using AJAX.</div>
You probably noticed this onclick="getDataFile(1)"
. With this we
are telling JavaScript that when the user clicks this element do whatever is inside the quotes. In our case
we want JavaScript to call the getDataFile(1)
function (which you will see
further down). Now, the value you see in brackets is called an argument and it represents the unique ID
of the content stored on the server. The argument will be sent to the function when called. This ID is very
important as it will help to know which data needs to be displayed. But don’t worry if it’s not very clear,
we will come back to that.
CSS
For those interested in how I styled my buttons here is the CSS (I like my buttons).
.button {
width: 90px;
margin-top: 20px;
padding: 15px;
font-weight: 400;
background-color: rgb(175, 66, 107);
color: rgba(255, 255, 255, 0.901961);
text-align: center;
text-shadow: rgba(0, 0, 0, 0.701961) 0px -1px 0px;
box-shadow: rgba(255, 255, 255, 0.0980392) 0px 0px 0px 1px inset,
rgba(255, 255, 255, 0.701961) 0px 4px 7px -4px inset,
rgba(255, 255, 255, 0) 0px 56px 47px -41px inset,
rgba(0, 0, 0, 0.498039) 0px 0px 8px -1px;
background-image: linear-gradient(to top, rgba(0, 0, 0, 0.4), transparent);
border-radius: 3px;
border: 0;
cursor: pointer;
}
JavaScript & MySQL
First we will see how we use AJAX pure JavaScript to get data from a MySQL database.
JavaScript
To start you need to create an XMLHttpRequest
object which will
allow to exchange data with the server without refreshing the page.
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert('Error');
}
}
}
Do you remember the function we call when clicking the button? There it is. And you will see
that the ID value we talked about is assigned to a variable called pageid
.
function getDataFile(pageid){
var container = document.getElementById("wrap-container"),// Gets container element
request = getXmlHttpRequestObject(),// Calls getXmlHttpRequestObject function
value = encodeURIComponent(pageid),
the_data = "id="+value;// We build the URL variable
container.innerHTML = "Loading...";// Lets the user know what's happening
// Sends request to server and set PHP file path containing the SQL query to connect to the database
request.open("POST", "getcontent.php", true);
// Allows to send data using POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data);
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
// The requested data is sent from the database, stored in responseText
// and then pushed into the div container using innerHTML to finaly display
// it on the page.
container.innerHTML = request.responseText;
}
}
}
encodeURIComponent()
escapes some special characters, to learn more have a
look at the Developer
Mozilla website.
PHP
Before this works we need to add some PHP script. Create a PHP file getcontent.php
and add the following lines of code.
<?php
// Set the information to connect to your database
// It is recommended to put this in a separate file
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'yourpassword');
DEFINE ('DB_NAME', 'yourdatabase');
// Opens a connection to the database
$connect = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die
('Could not connect to MySQL: ' . mysqli_connect_error());
// We get the value sent by POST method
$id = $_POST['id'];
// SQL query to get the data from the database
$get_content = mysqli_query($connect, "SELECT content FROM table WHERE content_id = ".$id);
$row=mysqli_fetch_array($get_content);
// We can now close the connection
mysqli_close($connect);
// The send the result to the JavaScript which will then display it on the page
echo $row["tut_title"];
?>
JavaScript & XML
Coding with XML involves few changes in the JavaScript, let’s see how it works.
XML
First we are going to see how the XML file built. You need to create a file
which you can call data.xml
and copy the following code in it.
<?xml version="1.0" encoding="UTF-8"?>
<data>
<page>
<id>1</id>
<content>Welcome to the home page everyone.</content>
</page>
<page>
<id>2</id>
<content>Let me tell you a little bit about me... well you are not really here for that, right?</content>
</page>
<page>
<id>3</id>
<content>You would like to tell how much you like this website? Please do.</content>
</page>
</data>
XML allows you to create your own tags. You can change the tags name as long as there is
an open and closed tag. You also need to have a correct structure. Notice how I structured
the data. There is <data>
which wraps all the other
tags. Every page has its unique ID and content.
JavaScript
Again we need to create an XMLHttpRequest
object
the same way we already did so I am not going to repeat the code here. We are going
to use the same function name so let’s see how the rest of the JavaScript looks like.
function getDataFile(pageid){
var container = document.getElementById("wrap-content"),
xmlHttp = getXmlHttpRequestObject();
container.innerHTML = "Loading...";
// Sends request to server and set XML file path
xmlHttp.open("GET", "data.xml", true);
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
var xmlResponse = xmlHttp.responseXML,
root = xmlResponse.documentElement,
id = root.getElementsByTagName("id"),// Get <id> tags with data
content = root.getElementsByTagName("content"),// Get <content> tags with data
pcontent = "";
for(var i=0; i<id.length; i++){// We loop through the all <id> tags
var pid = id.item(i).firstChild.data;// Gets data inside the <id> tag
if(pageid==pid){// If the ID from the XML file is equal to the ID sent we go through
// Get data stored in the <content> tag
pcontent = content.item(i).firstChild.data;
}
}
container.innerHTML = pcontent;// Displays the result
}
}
}
JQuery & MySQL
JQuery is great to make your life easier by doing some work for you. So you are going to learn how to use this JavaScript library to get data from a MySQL database.
JQuery
Here I used the exact same PHP file as earlier. No changes need to be done on it so we are just going to focus on the jQuery script.
function getDataFile(pageid){
var container = $("#wrap-content");
container.html("Loading...");
$.ajax({
type: 'POST',
cache: false,
url: "getcontent.php",
data: {id:pageid},
success: function(data){// 'data' contains the server's response
container.html(data);
}
});
}
This is all you need, isn’t that easy? Just by using $.ajax
jQuery
makes automatically all the needed requests with the server for you.
JQuery & XML
The last section of this tutorial is focused on using AJAX with jQuery and an XML file.
JQuery
Again, in this example I used the same XML file data.xml
.
function getDataFile(pageid){
var container = $("#wrap-content");
container.html("Loading...");
$.ajax({
type: 'GET',
cache: false,
url: "data.xml",
dataType: "xml",
success: function(xml){
$(xml).find('page').each(function(){
var pid = $(this).find('id').text(),
pcontent = $(this).find('content').text();
for(var i=0; i<pid.length; i++){
if(pageid==pid){
container.html(pcontent);
}
}
});
}
});
}
Look at AJAX with JSON which is the second part of this tutorial.
Nice tut, but why not use json instead of XML?
@Kristian thanks for your comment. Actually AJAX with JSON will be in part 2 of this tutorial (coming soon).