Using AJAX and PHPIntroduction: What the Heck?That's a lot of acronyms for the typical eye, but I'll tell you what they are.
In common-internet today, you'll notice that every time you go to a web page, there's a fixed amount of content on that page. If you wanted to change the content of that page, you would need to load up another page on that website. However, some people had come up with an idea using standard web languages today to make it so that changing pages is a thing of the past, and leads into the future of interactive web applications. This method is called the AJAX, otherwise known as Asynchronous JavaScript and XML.
For those not too web-savvy with this technical mumbo-jumbo, here's a quick way on how the internet works.
A user, using a client, namely an internet browser, will select pages by changing the URL, or address of that browser. The browser sends a request to that address, which retrieves data from the server, copies it, and brings it back to the browser to view.
That's just the typical process of how to view one webpage. To view another, you do the same thing. However, people wanted a way to load data from other pages without having to load another web page. This is where AJAX starts to kick in.
When an AJAX application is ran, an object is created that is called a Request that will work with your browser. Upon that request, actions are ran that will determine which file to load up, then will load that file, and all without changing your page. AJAX will request that file for you without having to make you change pages. When AJAX loads that file, whatever output that file results in is the response that is gained from running that file, whether it's an HTML page or a dynamic page. Your script that you create determines where to place that response or what to do with it.
So let's move onto the next bit now, since you have an understanding of what's going on with your AJAX applications.
JavaScript vs. PHPOften people ask "why do we use AJAX applications?". Well, in the world of programming, one language can do more than another, in which case, JavaScript can do things PHP can't do, and PHP can do things JavaScript can't do.
JavaScript is a client-side scripting language that is run on browsers. It's capable of doing simple things like printing and relaying data, math, and regular expressions. However, the weakness is that it's client-side, meaning all the work is done on the client. It has a giant dependancy on the user and their browser, and if they don't use a proper browser, they may or may not be able to run your script. However, since it is run on the client-side, it is able to do dynamic actions that dictate events for webpages, like animating text, or creating interactive forms.
PHP (Pre-Hypertext Processor) is a simple server-side language that will run code when the browser makes a request to the server. When a request to the server is made, the code is ran. This is commonly used on a lot of web pages that have dynamic content, like news aggregators or online stores. Since it is run on a server, anyone can see the output of that code. And a server-side language is more functional than a client-side language because a server can interact with the server more, in terms of databases or alternate packages that may be bundled. However, it's weakness is that in order to acquire new content, you need to change the page.
So we want to create a dynamic page that we never have to change pages for certain content. How do we do that?
Well, let's combine the two to create an ultimate weapon - AJAX!
Ultimately, AJAX can be used with any other server-side language, but these methods can only be done with JavaScript. Hence the name AJAX.
GoalOur objective in this is to create a dynamic form that will run a script and execute based upon our input.
But what should we do? Well let's see, how about we make a simple Hello World application! Except this will print whatever we put into the form
Creating the FormTo create the form, we're just going to use basic HTML. It's not too hard to follow along with the idea of HTML, as it uses a form of tagging. For each piece of any website, there's an HTML tag that contains that data. Like say a navigation bar holds the links to navigate the other pages of a website. In any case, it's not hard to scrap together an HTML website.
Copy this HTML code and save it as, well, I don't know, "AJAX.html"? Keep it in a folder as we'll be placing some other things next to it.
<html>
<head>
<title>First AJAX Application!</title>
<script type='text/javascript' src='Hello.js'></script>
</head>
<body>
<h1>First AJAX Application!</h1>
<p>Enter some text here!</p>
<form name='Hello'>
<input type='text' name='TextBar' onkeyup='HelloWorld()' />
</form>
<div id='replace'>Response will go here!</div>
</body>
</html>
This is our first webpage basically. There are a few key components here:
1. The <script> tag up top locates our JavaScript file for us
2. The <form> tag will let us know where our input is
3. The <input> tag is where our input text will go
3a. The attribute 'onkeyup' is what we want to do when a keyboard key is released
4. The <div> tag at the bottom is where we will put the response text
But all that's missing is the JavaScript. Without that, we don't really have any interactivity here.
The first step is, we need to create a function that will request the most essential AJAX component, the XMLHttpRequest. This works different per browser, so we need to have some function that will create that object on the fly for most browsers. For browsers like Internet Explorer 5 and 6, the object is called ActiveXObject, but most webviewers today use higher-grade browsers.
Let's make a function that will return the object depending on the browser.
// Return the XMLHttpRequest object depending on browser
// A function will stop executing when a return is met
function GetXmlHttpObject(){
// If we encounter
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject){
// code for IE6 and IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
// If nothing worked, let's alert them that their browser does not work
alert("Warning: your browser is not compliant with Asynchronous JavasScript and XML. Please use a browser that is.");
return null;
}
Now that we have a function to set us up with the XMLHttp part of AJAX, we can get to work on making the main function that will run.
Most of how this function is explained in the comments.
// Here is our defined AJAX function
function HelloWorld(){
// Retrieve the data from the text bar
var text = window.document.Hello.TextBar.value;
// And then let's save the Div for where we want to replace text
var div = window.document.getElementById("replace");
// If the string is not empty, we'll start the function
if(text.length != 0){
// First let's create the XMLHttp object - save it as Hello, simple as that
var Hello = GetXmlHttpObject();
// Then we need to specify a file and the query to send
var file = "Hello.php";
// We'll display a message that basically lets us know the JavaScript has worked up to this part
// This will get overwritten if the AJAX works
div.innerHTML = "Hold on...";
// Now the next part is tricky
// Usually a lot of AJAX scripts will define several functions to do this part
// Instead, we can keep it to one simple function by doing the following
// An XMLHttp object has a state to say when it's ready, called 'onreadystatechange'
// When the XMLHttp object is ready, we execute the code that is defined under 'onreadystatechange'
Hello.onreadystatechange = function(){
// There are also number indicators to tell you the exact state of the object
// The int 4 means that the XMLHttp object is ready to start workin'
// So here is where we will process the response text given by the queried file
if(Hello.readyState == 4){
// Send the information to the div now
// The XMLHttp object now has a property 'responseText'
div.innerHTML = Hello.responseText;
}
}
// Here is where we will do some quick file commands
// Likewise, we need the file and a query, so let's send the text to the query by joining the information
var query = "?q=" + text;
// Now to let the XMLHttp open up that file
Hello.open("GET", file+query, true);
// Send the data, leave the parameter null
Hello.send(null);
// And that's the end of the AJAX part!
// If a message is typed in, it will be sent to the Div with whatever the script chooses to do with the text
}else{
// Of course if the text string IS empty, we'll just simply give a message to the user
div.innerHTML = "You didn't type in anything!";
}
// And so ends our AJAX function
// This will be called whenever a key is released in the text bar on the HTML page
// Now we go to the PHP script to see what happens when this function is called
}
And likely, after all that, we need a PHP script that will work with the text. So up to this part, we have a function that will send whatever text is in the input bar, to a PHP script, and whatever comes out of that PHP script is our response text.
Here is the code for the basic PHP script that we will use.
<?php
// We need to grab the data from the URL header that we sent
// Using a $_GET variable, we can do such
$text = $_GET['q'];
// Now to display the information
// Since we're not doing anything overly complex, let's just make it something basic like merging strings
print "You said: " . $text;
?>
And all combined, if it all works, you should get an AJAX application working when you load up that HTML file containing the application.
So what does this basically mean for us? How can we apply this to our web-development lives?
Well, in a way, if you develop practical web applications, you might also want to think about using AJAX to save time of loading pages. Not only does it make your applications easier to use, it also reduces the stress of loading times when one person has to wait a particular amount of time for one file to load.
Since you can mix JavaScript and PHP together, you can do a lot of server-side work (like searching for database entries, sending e-mails, even sockets and networking). It allows you to treat web pages like a real desktop application with the same level of interaction.
There are of course, other frameworks out there that can make AJAX a lot easier, like jQuery or Mootools. Those are more aimed at making writing AJAX applications a lot easier.
Hopefully this tutorial helped you in the understanding (and possible interest) in creating your own AJAX applications!