Ajax basics
In this article I don't want to show you the history of AJAX and discuss its pros and cons, but only focus on how to create a basic working AJAX - PHP communication.
The only important thing at the moment is that AJAX uses JavaScript so it need to be enabled in your browser to successfully complete this tutorial.
To demonstrate the AJAX PHP connection we will create a very simple form with 2 input fields. In the first field you can type any text and we will send this text to our PHP script which will convert it to uppercase and sends it back to us. At the end we will put the result into the second input field. ( The example maybe not very useful but I think it is acceptable at this level. )
So let's list what we need to do:
- Listen on key-press event on the input field.
- In case of key-press send a message to the PHP script on the server.
- Process the input with PHP and send back the result.
- Capture the returning data and display it.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax - PHP example</title> </head> <body> <form name="testForm"> Input text: <input type="text" onkeyup="doWork();" name="inputText" id="inputText" /> Output text: <input type="text" name="outputText" id="outputText" /> </form> </body> </html>Javascript F1
But what is this doWork() and how we can send messages to the server script? On the next page you will find the answers.
The master - detail concept
Time to time you need to create web forms where your visitors can select first a main category and then a subcategory. Think a bit, it is not so easy to implement this solution. Why? You need to fill the first (master) list and the second (detail) list as well. However at design time you don't know which value is selected in the master list so how you should fill the detail page?Let's see an example:
Main category items:
- Audi
- BMW
- Mercedes
- Lexus
- A3, A4, A6, A8 for Audi
- 320, 520, 630, 745 for BMW
- A180, C200, E320, S500 for Mercedes
- IS200, GS300, LS600 for Lexus
Code:
<select name="brand" id="brand" onchange="doWork();"> <option value="Audi">Audi</option> <option value="BMW">BMW</option> <option value="Mercedes">Mercedes</option> <option value="Lexus">Lexus</option> </select> AJAX F1
Code:
<select name="type" id="type"> <option value="1">A3</option> <option value="2">A4</option> <option value="3">A6</option> <option value="4">A8</option> </select>AJAX F1
And here comes AJAX to help us. We will send a message to the server when the visitor have changed the value of the master select box. The server will construct a list of relevant detail items and sends back to the browser. Afterwards the browser assigns this list to the detail list.
Now let's see how to implement it.
AJAX file upload
First of all I have to say that to create a pure AJAX file upload system is not possible because of security limitations of JavaScript. All of the Ajax upload systems I know use some third party tool/package or only mimics the AJAX feeling. Even so it makes file upload process a bit nicer. In the next section I will present you a solution which imitates the AJAX process, but uses a normal upload process and iFrames.The concept:
- Create a simple HTML form for file upload
- Set the target to an iFrame which is on the actual page but not visible
- Call a JavaScript function on form submit to display the animation
- After the PHP part finishes the upload process, then it hides the animation
The HTML file we will use in this article is quite simple. It just have a simple form with a file field and a submit button. However don't forget about the enctype parameter.
Code:
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" > <input name="myfile" type="file" /> <input type="submit" name="submitBtn" value="Upload" /> </form>AJAX F1
Code:
<body> <p id="f1_upload_process">Loading...<br/><img src="loader.gif" /></p> <p id="result"></p> <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" > File: <input name="myfile" type="file" /> <input type="submit" name="submitBtn" value="Upload" /> </form> <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe> </body>AJAX F1
Code:
function startUpload(){ document.getElementById('f1_upload_process').style.visibility = 'visible'; return true; }AJAX F1
Code:
function stopUpload(success){ var result = ''; if (success == 1){ document.getElementById('result').innerHTML = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>'; } else { document.getElementById('result').innerHTML = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>'; } document.getElementById('f1_upload_process').style.visibility = 'hidden'; return true; }AJAX F1
Code:
#f1_upload_process{ z-index:100; position:absolute; visibility:hidden; text-align:center; width:400px; margin:0px; padding:0px; background-color:#fff; border:1px solid #ccc; } form{ text-align:center; width:390px; margin:0px; padding:5px; background-color:#fff; border:1px solid #ccc; }AJAX F1
Server side code:
The server side code is written in PHP and it is very short and simple. First we need to set the file destination path. In this case we will use the actual working directory. Afterwards we introduce a variable that shows if there was an error or not during the upload process. Next we move the uploaded file from the tmp directory to it's defined location and set the result variable if upload was success. At the end I have inserted a sleep command to make animation a bit longer in case of very fast uploads.
Now the end the PHP code looks like this:
Code:
<?php $destination_path = getcwd().DIRECTORY_SEPARATOR; $result = 0; $target_path = $destination_path . basename( $_FILES['myfile']['name']); if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) { $result = 1; } sleep(1); ?> AJAX F1
The output of the PHP code will be displayed / executed inside the iFrame. As you remember the iFrame is not visible, however we can call a JavaScript function here. And exactly this is the point where we can call the JavaScript function defined in the HTML code to hide the progress animation and display the file upload result on the main page. We can do it with the following JavaScript code:
Code:
<script language="javascript" type="text/javascript"> window.top.window.stopUpload(<?php echo $result; ?>); </script>
Ajax click tracking
There are many ways how to record your visitors activity on your page. In the next section I will show you one solution with Ajax and a small PHP code. Using this method your links still be Google friendly.First of all if you have no experience with Ajax then it could help to read a basic Ajax tutorial.
To implement the click tracking tool we need to create 2 files:
- clickDemo.html: This file contains the html with the links and the Ajax code.
- clickTrack.php: This files will be called by Ajax and records the click event.
Code:
<body> <a href="http://www.ajaxf1.com" onclick="doWork(this);" >Test</a> </body>AJAX F1
Code:
function doWork(element){ httpObject = getHTTPObject(); if (httpObject != null) { dst = element.href; src = document.location.href; httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true); httpObject.send(null); httpObject.onreadystatechange = setOutput; } }AJAX F1
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax click tracking example</title> <script language="javascript" type="text/javascript"> function getHTTPObject(){ if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else { alert("Your browser does not support AJAX."); return null; } } // Change the value of the outputText field function setOutput(){ return true; } // Implement business logic function doWork(element){ httpObject = getHTTPObject(); if (httpObject != null) { dst = element.href; src = document.location.href; httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true); httpObject.send(null); httpObject.onreadystatechange = setOutput; } } var httpObject = null; var src = null; var dst = null; </script> </head> <body> <a href="http://www.ajaxf1.com" onclick="doWork(this);" > Test </a> </body> </html>- clickDemo.html: This file contains the html with the links and the Ajax code.
- clickTrack.php: This files will be called by Ajax and records the click event.
Step 1 - Ajax click tracking
There are many ways how to record your visitors activity on your page.
In the next section I will show you one solution with Ajax and a small PHP code.
Using this method your links still be Google friendly.
First of all if you have no experience with Ajax then it could help to read a basic Ajax tutorial.
To implement the click tracking tool we need to create 2 files:
In this example the html body is as simple as possible to focus on the actual task. It looks like this:
Code:
<body> <a href="http://www.ajaxf1.com" onclick="doWork(this);" >Test</a> </body>
The javascript code is a bit more but here only the doWork() function is really interesting for us. This function will process the mouse click, get the source and target locations and call the clickTrack.php to update the statistic. The code is the following:
Code:
function doWork(element){ httpObject = getHTTPObject(); if (httpObject != null) { dst = element.href; src = document.location.href; httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true); httpObject.send(null); httpObject.onreadystatechange = setOutput; } }AJAX F1
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax click tracking example</title> <script language="javascript" type="text/javascript"> function getHTTPObject(){ if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else { alert("Your browser does not support AJAX."); return null; } } // Change the value of the outputText field function setOutput(){ return true; } // Implement business logic function doWork(element){ httpObject = getHTTPObject(); if (httpObject != null) { dst = element.href; src = document.location.href; httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true); httpObject.send(null); httpObject.onreadystatechange = setOutput; } } var httpObject = null; var src = null; var dst = null; </script> </head> <body> <a href="http://www.ajaxf1.com" onclick="doWork(this);" > Test </a> </body> </html>
Step 2 - The server side script
As you could see the onClick event triggers the doWork() javascript function on the clickDemo.html file. The doWork() function calls (visits) the server side script clickTrack.php and pass the source and target information as URL parameters. It means we need to process the $_GET array in the PHP code.If we get the variables then we can simply write them into a text file and that's it. The code is small and simple:
Code:
<?php $src = isset($_GET['src']) ? $_GET['src'] : "-"; $dst = isset($_GET['dst']) ? $_GET['dst'] : "-"; $f = fopen('clickReport.txt',"a+"); fwrite ($f, date('Y-m-d H:i')); fwrite ($f, " : " + $src + " : " + $dst + "\r\n"); fclose($f); ?>
Details
Max's AJAX Rating System
Max's AJAX Rating System is a simple, easy to install script which allows your visitors to rate any item on your page. You can put as many rating boxes on your page as you want. Vistors can rate only once. No database is required.

Tidak ada komentar:
Posting Komentar