Sei sulla pagina 1di 71

AJAX

Definition of AJAX
AJAX, which stands
for Asynchronous JavaScript And XML, is a
technique that allows web pages to be
updated asynchronously, which means
that the browser doesn't need to reload
the entire page when only a small bit of
data on the page has changed.
Ajax allows to create server connections
in the background while a user is
interacting with a Web front-end. These
connections can be created
asynchronously, which means that the
user need not wait until the server replies.
AJAX allows web pages to communicate
with the server behind the scenes. AJAX
passes only the updated information to
and from the server.
The word "asynchronous" means that the
user need not wait until the server
replies.
(Asynchronous (in Ajax) processes
incoming requests in a constant event
stack and sends small requests one
after the other without waiting for
responses. In other words, asynchronous
ajax call allow the next line of code to
execute, whereas synchronous call stop
JavaScript execution until the response
from server.)
Ajax is client side script that
communicates with web server.
Synchronous vs Asynchronous
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until
operation completes i.e. browser is unresponsive.
In such case, javascript engine of the browser is
blocked.
Asynchronous (AJAX Web-Application Model)
An asynchronous request doesn’t block the
client i.e. browser is responsive. At that time,
user can perform another operations also. In
such case, javascript engine of the browser is
not blocked.
Why synchronization is used
For example, you might need to handle
some transaction processing in which the
order is important. Consider a case in
which a web page needs to return a
confirmation page after the user
clicked something. This task requires
synchronizing the requests.
It is not a programming language.
It just uses a combination of :
◦ A browser built –in XMLHttpRequest object
(to request data from a web server)
◦ JavaScript and HTML DOM
(to display or use the data)
◦ AJAX is no programming or script language, no
new invention and no separate Web service,
module or plug-in. It is a group of inter-related
technologies like javascript, dom, xml, html, css
etc.
Following technology are used in AJAX:
HTML and CSS
These technologies are used for displaying
content and style. It is mainly used for
presentation.
DOM : It is used for dynamic display and
interaction with data.
XML or JSON
For carrying data to and from server. JSON
(Javascript Object Notation) is like XML but
short and faster than XML.
XMLHttpRequest
For asynchronous communication between
client and server.
Javascript
It is used to bring above technologies
together. It used for Client-side validation
and validate user input in an HTML form
before sending the data to a server.
What is the DOM?
The Document Object Model (DOM) is a
programming interface for HTML and
XML documents.
Your html
◦ Document :
page(document)
◦ Object: Elements and
attributes in your page
◦ Model: in DOM, tree structure of
html elements.
◦ It create tree structure of elements and
attributes of your html document in web
page.
Introduction to XML
XML stands for Extensible Markup
Language.
XML is a software and hardware
independent tool for storing and
transporting data.
XML is markup language much like HTML.
XML was designed to be self-descriptive.
XML is designed to carry data, not to
display data.
Difference Between XML
and HTML
XML was designed to carry data with
focus on what data is
HTML was designed to display data with
focus on how data looks.
XML tags are not predefined. You must
define your own tags.
Why use Ajax ?
AJAX allows you to send only important
information to the server not the
entire page. So only valuable data from
the client side is routed to the server
side.
It makes your application interactive
and faster.
AJAX can be used with javascript,
jquery and asp.net.(just way is different)
AJAX application might use XML to
send data, it could also use just plain
text or JSON text. But generally, it uses
an XMLHttpRequest object in your
browser (to request data from the
server) and JavaScript to display the
data.
l Google Suggest
AJAX was made popular in 2005 by Google,
with Google Suggest.
Google Suggest is using AJAX to create a very
dynamic web interface: When you start typing
in Google's search box, a JavaScript sends the
letters off to a server and the server returns
a list of suggestions without reload that page.
Features of AJAX
Uses of AJAX
There are too many web applications
running on the web that are using ajax
technology like;
Gmail
Facebook
Twitter
Google
Youtube
Ajax are mainly used where you want
to reload a part of web page but not
complete website or web-page. It make
any web-page faster.
XMLHttpRequest Object in Ajax

An object of XMLHttpRequest is used


for asynchronous communication
between client and server.
It performs following operations:
◦ Sends data from the client in the background.
◦ Receives the data from the server.
◦ Updates the webpage without reloading it.
Properties of XMLHttpRequest
object
Property Description
onReadyStateChange It is called whenever
readyState attribute changes. It must not
be used with synchronous requests.
readyState represents the state of the
request. It
ranges from 0 to 4.
0 request not initialized.
 1 OPENED open is called but send() is not
called.(server connection established)
2 send() is called, request recieved
3 loading Downloading data, processing
request
4 DONE The operation is completed fully.
(request finished and response is ready)
readyState can actually be 0-4.
Each time the state changes, an
onreadystatechange event occurs.
A new XMLHttpRequest object starts in
state 0
When you successfully call open() on the
object, the status changes to 1
When you successfully call send() on the
object, an HTTP request goes off to the
server defined in open(). Once the HTTP
response headers have been received and
processed the status changes to 2
Eventually, the actual content of the
request will start coming in. When this
begins, the status changes to 3
Finally, once all of the content is
downloaded and is ready to be used, the
status changes to 4
How to create an XMLHttpRequest and receive response
from the server.
1. Create XMLhttpRequest
var xmlhttp=new XMLHttpRequest();
2. Sending request to the server
To send off a request to the server, we use the open()
method and the send() method.
xmlHttp.open(“GET”,”time.asp”,true);
xmlHttp.send(null);
The open() method takes three arguments.
 The first argument defines which method to use
when sending the request (GET or POST).
The second argument specifies the URL of the
server-side script.
 The third argument specifies that the request
should be handled asynchronously.
The send() method sends the request off to
the server.
Methods of XMLHttpRequest Object
Property
1. void open(method, URL)
opens the request specifying get or post
method and url.
2. void open(method, URL, async)
same as above but specifies
asynchronous or not.
3. void send()
sends get request.
4. void send(string)
send post request.
All modern browsers support the
XMLHttpRequest object (Except IE5 and
IE6 use an ActiveXObject).
The XMLHttpRequest object is 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.
<html>
<body>
<form>
<label>Choose state:</label>
<select onchange="myfun (this.value)">
<option>Select State</option>
<option>MP</option>
<option>UP</option>
</select>
<br>
<br>
<label>Choose City:</label>
<select id="city">
<option>Select City</option>
</select>
</form>
<script type="text/javascript">
function myfun(data)
{
alert(data);
var req=new XMLHttpRequest();
req.open("GET","http://localhost/ajax/response.php?
datavalue="+data,
true);
req.send();

req.onReadyStateChange=function(){
if(req.readyState==4 && req.status==200){
document.getElementbyId('city').innerHTML=req.
responseText;
}
} }
</script> </body> </html>
//response.php
<?php
$data=$_GET['datavalue'];

$a=array('Indore','Ujjain');
$b=array('Bihar','Luckhnow');

if($data=="MP"){
foreach($a as $a1){
echo "<option> $a1 </option>";
}
}
?>
<div id="loaddata">
<h2>Change that</h2>
</div>
<button onclick="myfunc()">Check</button>
<script type="text/javascript">
function myfunc(){
var req = new XMLHttpRequest();
req.open('GET','data.html',true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status ==
200){
document.
getElementById('loaddata').innerHTML=req.
responseText;
} }
} </script>
Ex 2
<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) {
document.getElementById("txtHint").
innerHTML = this.responseText;
}
}
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>
First name: <input type="text" onkeyup="
showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></
span></p>
</body>
<?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";
// 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;
?>
What is jQuery
jQuery is a small and lightweight
JavaScript library.
The main purpose of jQuery is to provide
an easy way to use JavaScript on your
website to make it more interactive and
attractive.
jQuery is cross-platform.
jQuery means "write less do more". For
perform any task Jquery required less
code compare to javascript.
jQuery simplifies AJAX call and DOM
manipulation.
Many of the biggest companies on the Web
use jQuery, such as: Google, Microsoft,
IBM
JQuery Feature
Simple and easy: It have predefined method using
you can perform any task easily compare to
JavaScript. And it is easy to learn.
Lightweight: It is very lightweight library - about
19KB in size ( Minified and gzipped ).
CSS manipulation: It have predefined css() method
for manipulate style for any Html elements.
Html manipulation: The jQuery made it easy to
select DOM elements, traverse them and modifying
their content.
Cross browser support: It support all modern web-
browser including IE-6.
Event handling: It support event handling like click
mouse button.
JavaScript Library: It is JavaScript library.
Ajax Support: It support ajax, you can develop a
responsive and feature-rich site using AJAX
technology.
Built-in Animation: It have predefined method "
animate()" for create custom animation on web-page.
Document Ready Event

It means jquery code load after


complete loading of web page.
Syntax
$(document).ready(function() {
// jQuery methods
});
Selectors
jQuery selectors are used to find or
select Html elements based on their id,
classes, types, attributes, values of
attributes etc..
Selector in jQuery is start with $ sign
and parentheses: $()
The jQuery selector enables you to find
DOM elements in your web page. Most of
the times you will start with selector
function $() in the jQuery.
Syntax
$(selector).action()
<?php /* The load() method loads data
from server and puts the returned data
into the selected element.
$(selector).load(URL,data,callback);
data and callback is optional*/?>
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/
HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$("#btn").click(function() {
$("#test").load("data.html");
/*$("#test").load("data.html",function(){
alert(This is done);
});*/
});
});
</script>
</head>
<body>
<div id="test">
<p>Count your life with smiles, not tears.!</p>
</div>
<button id="btn">Click to change</button>
</body>
</html>
jQuery Effects
jQuery enables us to add effects
on a web page. jQuery effects can
be categorized into fading, sliding,
hiding/showing and animation
effects.
jQuery Traversing

The jQuery selectors we've seen so far


only allow us to select the elements down
the DOM tree.
With these traversal methods, we can go
up, down, and all around the DOM tree
very easily.
The above diagram showing the parent/child
relationships between the elements:
The <body> element is theparent of
the <div> element, and anancestor of everything
inside of it. The enclosed <div> element is
theparent of <h1>, <p> and <ul> elements, and
child
a of the <body> element.
The elements <h1>, <p> and <ul> aresiblings , since
they share the same parent.
The <h1> element is achild of the <div> element
and adescendant of the <body> element. This
element does not have any children.
The <p> element is theparent of <em> element,
child of the <div> element and adescendant of
the <body> element. The containing <em> element
child of this <p> element and a
is a descendant of
the <div> and <body> element.
Similarly, the <ul> element is theparent of
the <li> elements,child of the <div> element and
adescendant of the <body> element. The
containing <li> elements are the child of
this <ul> element and descendant
a of
the <div> and <body> element. Also, both
the <li>elements aresiblings .
jQuery parent() Method

The jQuery parent() method is used to


get the direct parent of the selected
element.
The following example will highlight the
direct parent element of the <li> which
is <ul> by adding the class highlight on
document ready.
<html lang="en">
<head>
<title>Selecting the Direct Parent Element in jQuery</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></
script>
<script type="text/javascript">
$(document).ready(function(){
$("li").parent().addClass("highlight");
});
</script> </head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div> </body> </html>
jQuery children() Method

The jQuery children() method is used to


get the direct children of the selected
element.
The following example will highlight the
direct children of the <ul> element which
is <li> by adding the class highlight on
document ready.
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selecting the Direct Child Elements in jQuery</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></
script>
<script type="text/javascript">
$(document).ready(function(){
$("p").children().addClass("highlight");
});
</script> </head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div> </body> </html>
jQuery find() Method

The jQuery find() method is used to get


the descendant elements of the
selected element.
The find() and children() methods are
similar, except that the find() method
search through multiple levels down the
DOM tree to the last descendant,
whereas the children() method only
search a single level down the DOM tree.
The following example will add a border
around all the <li>elements that are
descendants of the <div> element.
<html lang="en">
<head>
<title>Selecting the Specific Descendant Elements in jQuery</title>
<style type="text/css">
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></
script>
<script type="text/javascript">
$(document).ready(function(){
$("div").find("ul").addClass("frame");
});
</script> </head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div> </body> </html>
jQuery siblings() Method

The jQuery siblings() method is used to


get the sibling elements of the selected
element.
The following example will highlight the
siblings of the <p> element which
are <h1> and <ul> by adding the class
highlight on document ready.
<html lang="en">
<head>
<title>Selecting All the Sibling Elements in jQuery</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></
script>
<script type="text/javascript">
$(document).ready(function(){
$("ul").siblings().addClass("highlight");
});
</script> </head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div> </body> </html>
jQuery Events
jQuery events are the actions that
can be detected by your web application.
They are used to create dynamic web
pages. An event shows the exact moment
when something happens.
These are some examples of events.
A mouse click
An HTML form submission
A web page loading
A keystroke on the keyboard
Scrolling of the web page etc.
Mouse Events
Click dblclick mouseenter
mouseleave
Keyboard Events
Keyup keydown keypress
Form Events
Submit change blur focus
Document/Window Events
Load unload scroll resize
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/
jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".para").dblclickfunction(){
$(this).hide();
});
});
</script> </head> <body>
<p>Click on below text, I will disappear.</p>
<p class="para">Click me please!</p>
<p class="para">Click me too!</p>
</body> </htm>
// click, dblclick,mouseenter, mouseleave
jQuery keydown()
When you press a key on the keyboard,
the keydown() event is occurred and
once the keydown() event is occurred, it
executes the function associated with
keydown() method to run.
The keydown() event is generally used
with two other events.
Keypress() event: It specifies that the key
is pressed down.
Keyup() event: It specifies that the key is
released.
Syntax:
$(selector).keydown()
<html>
<head>
<script src="https://code.jquery.com/
jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("input").keydown(function(){
$("input").css("background-color", "green");
});
$("input").keyup(function(){
$("input").css("background-color", "violet");
});
});
</script> </head>
<body>
Write something: <input type="text">
</body> </html>
Keypress Event
<html>
<head>
<script src="https://code.jquery.com/
jquery-1.10.2.js"></script>
<script>
i = 0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text (i += 1);
});
});
</script>
</head>
<body>
Write something: <input type="text">
<p>Keypresses: <span>0</span></p>
</body> </html>
Form event: submit
<html lang="en">
<head>
<meta charset="utf-8">
<title>submit demo</title>
<style>
p{
margin: 0;
color: blue;
}
div,p {
margin-left: 10px;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/
jquery-1.10.2.js"></script>
</head>
<body>
<p>Type 'wonder' to submit this form finally.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
<script>
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "wonder" ) {
$( "span" ).text( "Submitted Successfully." ).
show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut(
2000 );
event.preventDefault();
});
</script> </body> </html>
Form events:blur
The jQuery blur event occurs when element loses
focus. It can be generated by via keyboard
commands like tab key or mouse click anywhere on
the page.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js">
</script>
<script>
$(document).ready(function(){
$("input").blur(function(){
alert("This text box has lost its focus.");
});
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body>
</html>
The jQuery focus event occurs when an element gains
focus. It is generated by a mouse click or by navigating
to it.
<html lang="en"> <head>
<style>
span {
display: none;
color:red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></
script>
</head>
<body>
<p><input type="text"> <span>Focus starts.. Write your
name.</span></p>
<p><input type="password"> <span>Focus starts.. Write
your password.</span></p>
<script>
$( "input" ).focus(function() {
$( this ).next( "span" ).css( "display", "inline" ).fadeOut(
2000 );
});
</script> </body> </html>
EX : AJAX+mysql
<body>
<!--The "message" id will be display via
PHP and AJAX-->
<p id="message"></p>
<form id="my-form" action="" method="
post">
<input type="text" name="name"
placeholder="Name" required>
<input type="number" name="age"
placeholder="Age" required>
<button type="submit">Insert</
button>
</form>
</body>
</html>
<html> <head>
<title>Inserting Form Data Into MySQL
Using PHP and AJAX</title>
<script src="https://ajax.googleapis.com/
ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
<!--#my-form grabs the form id-->
$("#my-form").
submit(function(e) {
e.preventDefault();//The event.
preventDefault() method stops the default action of
an element from happening. Prevent a submit button
from submitting a form
Prevent a link from following the URL
$.ajax( {
<!--insert.php calls the PHP
file-->
url: "insert.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success:
function(strMessage) {
$("#message").
text(strMessage);
$("#my-form")[0].reset();
} }); });
);
// insert.php
<?php
//Connection to MySQL
$con = mysqli_connect('localhost', 'root', '');

if(!$con) {
die('Not Connected To Server');
}

//Connection to database
if(!mysqli_select_db($con, 'test')) {
echo 'Database Not Selected';
}
//Create variables
$name = $_POST['name'];
$age = $_POST['age'];
$query = mysqli_query($con,"SELECT *
FROM user WHERE name='$name' OR
age='$age'");
$sql = "INSERT INTO user (name, age)
VALUES ('$name', '$age')";

//Make sure name is valid


if(!preg_match("/^[a-zA-Z'-]+$/",$name)) {
die ("invalid first name");
}
//Response
//Checking to see if name or email already exsist
if(mysqli_num_rows($query) > 0) {
echo "The name, " . $_POST['name'] . ", or
age, " . $_POST['age'] . ", already exists.";
}
elseif(!mysqli_query($con, $sql)) {
echo 'Could not insert‘; }
else {
echo "Thank you, " . $_POST['name'] . ".
Your information has been inserted.";
}
mysqli_close($con); //Close connection
?>
The $.get() method requests data from
server with an HTTP GET request.
Syntax :
$.get(URL,Callback);
The optional callback parameter is the
name of a function to be executed if
the request succeeds.
$.post() method requests data from the
server using an HTTP POST request.
Syntax
$.post(URL,data,callback);
The required url parameter specifies the
URL you wish to request.
The optional data parameter specifies
some data to send along with the
request.

Potrebbero piacerti anche