0% found this document useful (0 votes)
16 views

Computer Science

AJAX is a set of web development techniques using many web technologies on both the client-side and server-side to create asynchronous web applications. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes, without reloading the entire page. This is done through the XMLHttpRequest object in JavaScript along with DOM manipulation. The exchanged data can be HTML, XML, JSON or plain text.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Computer Science

AJAX is a set of web development techniques using many web technologies on both the client-side and server-side to create asynchronous web applications. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes, without reloading the entire page. This is done through the XMLHttpRequest object in JavaScript along with DOM manipulation. The exchanged data can be HTML, XML, JSON or plain text.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Ch-4

AJAX
• What is Ajax?
• AJAX full form is 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.The purpose of AJAX
is to exchange small amounts of data with server without
page refresh.
• 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.
• 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 a web development technique for
creating interactive web applications.
• If you know JavaScript, HTML, CSS, and XML,
then you need to spend just one hour to start
with AJAX.
• AJAX is a new technique for creating better,
faster, and more interactive web applications
with the help of XML, HTML, CSS, and Java
Script.
• Ajax uses XHTML for content, CSS for
presentation, along with Document Object
Model and JavaScript for dynamic content
display.
• Conventional web applications transmit
information to and from the sever using
synchronous requests. It means you fill out a
form, hit submit, and get directed to a new
page with new information from the server.
• With AJAX, when you hit submit, JavaScript
will make a request to the server, interpret the
results, and update the current screen.
• XML is commonly used as the format for
receiving server data, although any format,
including plain text, can be used.
• AJAX is a web browser technology
independent of web server software.
• Why use AJAX
• No page reload
• Less bandwidth
• Very interactive
• How AJAX Works
• 1. An event occurs in a web page (the page is
loaded, a button is clicked)
• 2. An XMLHttpRequest object is created by
JavaScript
• 3. The XMLHttpRequest object sends a request to
a web server
• 4. The server processes the request
• 5. The server sends a response back to the web
page
• 6. The response is read by JavaScript
• 7. Proper action (like page update) is performed
by JavaScript
• The XMLHttpRequest Object
• All modern browsers support the
XMLHttpRequest object.
• The XMLHttpRequest object can be used to
exchange data with a server behind the
scenes.
• This means that it is possible to update parts
of a web page, without reloading the whole
page.
• variable = new XMLHttpRequest();
• var xhttp = new XMLHttpRequest();
• The XMLHttpRequest Object
• All modern browsers support the
XMLHttpRequest object.
• The XMLHttpRequest object can be used to
exchange data with a server behind the
scenes. This means that it is possible to
update parts of a web page, without reloading
the whole page.
• XMLHttpRequest Object Properties
• onreadystatechange
• Defines a function to be called when the
readyState property changes
• readyState
• Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
• responseText
• Returns the response data as a string
• responseXML
• Returns the response data as XML data
• status
• Returns the status-number of a request
200: "OK"
403: "Forbidden"
404: "Not Found“
• XML httpRequest methods
• Abort()-cancel the request
• getAllResponseHeaders()-return the complete
set of http headers as string
• getResponseHeader(header name)-return
http header value
• Send a Request To a Server
• To send a request to a server, we use the
open() and send() methods of the
XMLHttpRequest object:
• xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
• send() Sends the request to the server (used
for GET)
• send(string) Sends the request to the server
(used for POST)
• AJAX with PHP
• var xmlhttp = new XMLHttpRequest(); //create
object
• xmlhttp.onreadystatechange = function() //call
function when state will change
• {
•if (this.readyState == 4 && this.status == 200)//4
means request complete,200 request is successful
• {
• document.getElementById(“demo").innerHTML =
this.responseText //update the demo i.e add
response to demo
• }
• };
• xmlhttp.open("GET", “ajax.txt”, true);
xmlhttp.send();
• In the example above, when a user types a
character in the input field, a function called
"showHint()" is executed.
• The function is triggered by the onkeyup
event.
• Here is the HTML code:
• <html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML
= "";
return;
}
• else
• {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
• {
• if (this.readyState == 4 && this.status ==
200)//4 means request complete,200 request is
successful
• {
• document.getElementById("txtHint").innerHT
ML = this.responseText; //response get from
server add to txthint
}
};
• xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field
below:</b></p>
<form action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
• Code explanation:
• First, check if the input field is empty (str.length == 0).
If it is, clear the content of the txtHint placeholder and
exit the function.
• However, if the input field is not empty, do the
following:
• Create an XMLHttpRequest object
• Create the function to be executed when the server
response is ready
• Send the request off to a PHP file (gethint.php) on the
server
• Notice that q parameter is added to the url
(gethint.php?q="+str)
• And the str variable holds the content of the input field
• gethint.php"
• <?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
• // get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
• AJAX XML Example
• Ajaxxml.jsp
• The following example will demonstrate how a web
page can fetch information from an XML file with AJAX:
• When a user clicks on the "Get CD info" button above,
the loadDoc() function is executed.
• The loadDoc() function creates an XMLHttpRequest
object, adds the function to be executed when the
server response is ready, and sends the request off to
the server.
• When the server response is ready, an HTML table is
built, nodes (elements) are extracted from the XML
file, and it finally updates the element "demo" with the
HTML table filled with XML data:
• Performing AJAX Validation
• <script type="text/javapoint">
var http=false;
if(navigator.appname=="Mozilla")
{
http =new ActivexObject("Mozilla")
}
else
{
http =new XMLHttpRequest();
}
function validate(name)
{
http.abort();
http.open("GET","validate.php?name=" +name,true);
http.onreadtstatechange=function()
{
• if(http.readystate ==4)
{
document.getElementById('res').innerHTML
=http.responseText;
}
}
http.send(null);
}
</script>
<h1>
Type username to choose</h1>
<form>
<input type="text" name="name"
onkeyup="validate(this.value)"/>
<div id="res"></div>
</form>
• validate
• <?php
function validate($name)
{
if($name==' ')
{
return 'please enter any username';
}
if(strlen($name)<3)
{
return "Username is too short.";
switch($name)
{
case 'xyz':
case 'pqr':
case 'abc':
case 'ppp';
return "username already exit.";
}
return "username is valid";
}
echo validate(trim($_REQUEST['name']));
?>
Connecting database using php and ajax
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}</script>
</head>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>
getuser.php
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = pg_connect('localhost','root');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
pg_select_db($con,"root");
$sql="SELECT * FROM ajax_demo WHERE id = '".$q."'";
$result = pg_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
• while($row=pg_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['job'] . "</td>";
echo "</tr>";
}
echo "</table>";
pg_close($con);
?>
</body>
</html>

You might also like