Minggu, 21 November 2010

Ajax PHP tutorial

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.
Our html code is very simple it looks like this:
Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title>Ajax - PHP example</title>
  7. </head>
  8. <body>
  9. <form name="testForm">
  10. Input text: <input type="text" onkeyup="doWork();" name="inputText" id="inputText" />
  11. Output text: <input type="text" name="outputText" id="outputText" />
  12. </form>
  13. </body>
  14. </html>
Javascript F1
As you can see there is a doWork() function which is called in every case when a key is up (a key was pressed). Of course you can use any other supported events if you want.
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
And the subcategories are:
  • A3, A4, A6, A8 for Audi
  • 320, 520, 630, 745 for BMW
  • A180, C200, E320, S500 for Mercedes
  • IS200, GS300, LS600 for Lexus
So to fill the master list is quite simple, just add the 4 car brand to the list as here:
Code:
  1. <select name="brand" id="brand" onchange="doWork();">
  2. <option value="Audi">Audi</option>
  3. <option value="BMW">BMW</option>
  4. <option value="Mercedes">Mercedes</option>
  5. <option value="Lexus">Lexus</option>
  6. </select>
AJAX F1
In case of the detail list we have the problem what items to add. If Audi is the first then the detail select box should look like this:
Code:
  1. <select name="type" id="type">
  2. <option value="1">A3</option>
  3. <option value="2">A4</option>
  4. <option value="3">A6</option>
  5. <option value="4">A8</option>
  6. </select>
AJAX F1
But if the visitor made any changes in the master list then our detail list items still the same.
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
Creating the HTML file:
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:
  1. <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" >
  2. <input name="myfile" type="file" />
  3. <input type="submit" name="submitBtn" value="Upload" />
  4. </form>
AJAX F1
Besides this we need to add a bit more code to it. First we need a block where we will display the progress animation. We need an other block where we inform the visitor whether the upload was success or not. Besides this we need to add a hidden iFrame to the page which is used as the form target. At least we add an onSubmit event to the form. So our HTML body looks like this:
Code:
  1. <body>
  2. <p id="f1_upload_process">Loading...<br/><img src="loader.gif" /></p>
  3. <p id="result"></p>
  4. <form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
  5. File: <input name="myfile" type="file" />
  6. <input type="submit" name="submitBtn" value="Upload" />
  7. </form>
  8. <iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
  9. </body>
AJAX F1
By default the progress animation block content is hidden. We need a JavaScript function which makes this block visible if the submit button was pressed. It is a very simple code, that only changes the visibility parameter.
Code:
  1. function startUpload(){
  2. document.getElementById('f1_upload_process').style.visibility = 'visible';
  3. return true;
  4. }
AJAX F1
Besides this we need an other function, what we will call at the end of the upload process. This code will be print out a result message depending on it's parameter and hides the progress block again.
Code:
  1. function stopUpload(success){
  2. var result = '';
  3. if (success == 1){
  4. document.getElementById('result').innerHTML =
  5. '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
  6. }
  7. else {
  8. document.getElementById('result').innerHTML =
  9. '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
  10. }
  11. document.getElementById('f1_upload_process').style.visibility = 'hidden';
  12. return true;
  13. }
AJAX F1
Before we creating the PHP code we still need to create a style for the form and the progress block. The form style is very simple, but the progress block style sets the z-index, position and visibility parameter as well.
Code:
  1. #f1_upload_process{
  2. z-index:100;
  3. position:absolute;
  4. visibility:hidden;
  5. text-align:center;
  6. width:400px;
  7. margin:0px;
  8. padding:0px;
  9. background-color:#fff;
  10. border:1px solid #ccc;
  11. }
  12. form{
  13. text-align:center;
  14. width:390px;
  15. margin:0px;
  16. padding:5px;
  17. background-color:#fff;
  18. border:1px solid #ccc;
  19. }
AJAX F1
Now we can focus on the server side.
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:
  1. <?php
  2. $destination_path = getcwd().DIRECTORY_SEPARATOR;
  3. $result = 0;
  4. $target_path = $destination_path . basename( $_FILES['myfile']['name']);
  5. if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
  6. $result = 1;
  7. }
  8. sleep(1);
  9. ?>
AJAX F1
Finish the work from iFrame:
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:
  1. <script language="javascript" type="text/javascript">
  2. window.top.window.stopUpload(<?php echo $result; ?>);
  3. </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:
  1. clickDemo.html: This file contains the html with the links and the Ajax code.
  2. clickTrack.php: This files will be called by Ajax and records the click event.
In this example the html body is as simple as possible to focus on the actual task. It looks like this:
Code:
  1. <body>
  2. <a href="http://www.ajaxf1.com" onclick="doWork(this);" >Test</a>
  3. </body>
AJAX F1
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:
  1. function doWork(element){
  2. httpObject = getHTTPObject();
  3. if (httpObject != null) {
  4. dst = element.href;
  5. src = document.location.href;
  6. httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true);
  7. httpObject.send(null);
  8. httpObject.onreadystatechange = setOutput;
  9. }
  10. }
AJAX F1
Now let's put everything together in the clickDemo.html file. The complete code looks like this:
Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title>Ajax click tracking example</title>
  7. <script language="javascript" type="text/javascript">
  8. function getHTTPObject(){
  9. if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  10. else if (window.XMLHttpRequest) return new XMLHttpRequest();
  11. else {
  12. alert("Your browser does not support AJAX.");
  13. return null;
  14. }
  15. }
  16. // Change the value of the outputText field
  17. function setOutput(){
  18. return true;
  19. }
  20. // Implement business logic
  21. function doWork(element){
  22. httpObject = getHTTPObject();
  23. if (httpObject != null) {
  24. dst = element.href;
  25. src = document.location.href;
  26. httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true);
  27. httpObject.send(null);
  28. httpObject.onreadystatechange = setOutput;
  29. }
  30. }
  31. var httpObject = null;
  32. var src = null;
  33. var dst = null;
  34. </script>
  35. </head>
  36. <body>
  37. <a href="http://www.ajaxf1.com" onclick="doWork(this);" > Test </a>
  38. </body>
  39. </html>
  40. clickDemo.html: This file contains the html with the links and the Ajax code.
  41. 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:
  1. <body>
  2. <a href="http://www.ajaxf1.com" onclick="doWork(this);" >Test</a>
  3. </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:
  1. function doWork(element){
  2. httpObject = getHTTPObject();
  3. if (httpObject != null) {
  4. dst = element.href;
  5. src = document.location.href;
  6. httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true);
  7. httpObject.send(null);
  8. httpObject.onreadystatechange = setOutput;
  9. }
  10. }
AJAX F1
Now let's put everything together in the clickDemo.html file. The complete code looks like this:
Code:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title>Ajax click tracking example</title>
  7. <script language="javascript" type="text/javascript">
  8. function getHTTPObject(){
  9. if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
  10. else if (window.XMLHttpRequest) return new XMLHttpRequest();
  11. else {
  12. alert("Your browser does not support AJAX.");
  13. return null;
  14. }
  15. }
  16. // Change the value of the outputText field
  17. function setOutput(){
  18. return true;
  19. }
  20. // Implement business logic
  21. function doWork(element){
  22. httpObject = getHTTPObject();
  23. if (httpObject != null) {
  24. dst = element.href;
  25. src = document.location.href;
  26. httpObject.open("GET", "clickTrack.php?src="+src+"&dst="+dst, true);
  27. httpObject.send(null);
  28. httpObject.onreadystatechange = setOutput;
  29. }
  30. }
  31. var httpObject = null;
  32. var src = null;
  33. var dst = null;
  34. </script>
  35. </head>
  36. <body>
  37. <a href="http://www.ajaxf1.com" onclick="doWork(this);" > Test </a>
  38. </body>
  39. </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:
  1. <?php
  2. $src = isset($_GET['src']) ? $_GET['src'] : "-";
  3. $dst = isset($_GET['dst']) ? $_GET['dst'] : "-";
  4. $f = fopen('clickReport.txt',"a+");
  5. fwrite ($f, date('Y-m-d H:i'));
  6. fwrite ($f, " : " + $src + " : " + $dst + "\r\n");
  7. fclose($f);
  8. ?>

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.



Download Max's AJAX File Uploader

Tidak ada komentar:

Posting Komentar