How to create Ajax based PHP application

JavaScript is a client side scripting language. It is executed on the client side by the web browsers that support JavaScript. JavaScript code only works in browsers that have JavaScript enabled. It supports the following programming patterns;

  • Object oriented
  • Imperative
  • Functional

JavaScript enhances the functionality of websites and web applications. It is used to perform activities like.

  • Display a message box
  • Animate text or images on a web page
  • Open a pop up window
  • Update only a single part of a webpage
  • Perform validations on the client side

The syntax for JavaScript was inspired by the C Language syntax. The code below shows a JavaScript code that displays a message box.

1
<script>alert('Hello World!');</script>

HERE,

  • “<script>…</script>” are the opening and closing tags for JavaScript code when embedded into an HTML document
  • “alert(…);” alert is the built in function that displays a message box.
  • “’Hello World!’ “ is the string parameter that is displayed on the message box.

XML is the acronym for Extensible Markup Language. It is used to encode messages in both human and machine readable formats. It’s like HTML but allows you to create your custom tags. For more details on XML, see the article on XML

AJAX is the acronym for Asynchronous JavaScript And XML. It is a technology that reduces the interactions between the server and client. It does this by updating only part of a web page rather than the whole page. The asynchronous interactions are initiated by JavaScript.

Why use AJAX?
  • It allows developing rich interactive web applications just like desktop applications.
  • Validation can be performed done as the user fills in a form without submitting it. This can be achieved using auto completion. The words that the user types in are submitted to the server for processing. The server responds with keywords that match what the user entered.
  • It can be used to populate a dropdown box depending on the value of another dropdown box
  • Data can be retrieved from the server and only a certain part of a page updated without loading the whole page. This is very useful for web page parts that load things like
    • Tweets
    • Comments
    • Users visiting the site etc.
Creating an Ajax application

We will create a simple application that allows users to search for popular PHP MVC frameworks. Our application will have a text box that users will type in the names of the framework. We will then use AJAX to search for a match then display the framework’s complete name just below the search form.

Creating the index page

Index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
    <head>
        <title>PHP MVC Frameworks - Search Engine</title>
        <script type="text/javascript" src="https://cdn.guru99.com/auto_complete.js"></script>
    </head>
    <body>
        <h2>PHP MVC Frameworks - Search Engine</h2>
        <p><b>Type the first letter of the PHP MVC Framework</b></p>
        <form method="POST" action="index.php">
            <p><input type="text" size="40" id="txtHint"  onkeyup="showName(this.value)"></p>
        </form>
        <p>Matches: <span id="txtName"></span></p>
    </body>
</html>

HERE,

  • “onkeyup=”showName(this.value)”” executes the JavaScript function showName everytime a key is typed in the textbox. This feature is called auto complete
Creating the frameworks page

frameworks.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
$frameworks = array("CodeIgniter","Zend Framework","Cake PHP","Kohana") ;
$name = $_GET["name"];
if (strlen($name) > 0) {
    $match = "";
    for ($i = 0; $i < count($frameworks); $i++) {
        if (strtolower($name) == strtolower(substr($frameworks[$i], 0, strlen($name)))) {
            if ($match == "") {
                $match = $frameworks[$i];
            } else {
                $match = $match . " , " . $frameworks[$i];
            }
        }
    }
}
echo ($match == "") ? 'no match found' : $match;
?>

 

Creating the JS script

auto_complete.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<script>
function showName(str){
    if (str.length == 0){ //exit function if nothing has been typed in the textbox
        document.getElementById("txtName").innerHTML=""; //clear previous results
        return;
    }
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("txtName").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","frameworks.php?name="+str,true);
    xmlhttp.send();
}
</script>

HERE,

  • “if (str.length == 0)” check the length of the string. If it is 0, then the rest of the script is not executed.
  • “if (window.XMLHttpRequest)…” Internet Explorer versions 5 and 6 use ActiveXObject for AJAX implementation. Other versions and browsers such as Chrome, FireFox use XMLHttpRequest. This code will ensure that our application works in both IE 5 & 6 and other high versions of IE and browsers.
  • “xmlhttp.onreadystatechange=function…” checks if the AJAX interaction is complete and the status is 200 then updates the txtName span with the returned results.
Testing our application

Assuming you have saved the file index.php In phututs/ajax, browse to the URL  https://localhost/phptuts/ajax/index.php

ajax_index

Type the letter C in the text box You will get the following results.

ajax_results

The above example demonstrates the concept of AJAX and how it can help us create rich interaction applications.

  • AJAX is the acronym for Asynchronous JavaScript and XML
  • AJAX is a technology used to create rich interaction applications that reduce the interactions between the client and the server by updating only parts of the web page.
  • Internet Explorer version 5 and 6 use ActiveXObject to implement AJAX operations.
  • Internet explorer version 7 and above and browsers Chrome, Firefox, Opera, and Safari use XMLHttpRequest.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.