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

Unit 04 - Introduction to Ajax and JQuery

Uploaded by

Narendra Modi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit 04 - Introduction to Ajax and JQuery

Uploaded by

Narendra Modi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT 4

Introduction to Ajax and JQuery

1) What is AJAX?
AJAX stands for Asynchronous JavaScript and XML. It is a group of related technologies
used to display data asynchronously. In other words, it sends and retrieves data without reloading
the web page. ..

Ajax is a technique to exchange data without page reloads, that is a mix of tools
like JavaScript, HTML, DHTML, XML, CSS, DOM. It uses XMLHttpRequest
object for asynchronous data transfer, reducing bandwidth usage.
Various social media websites like Face book, Instagram, Twitter use the Ajax
technique to increase the count value when the user clicks the ‘Like’ button
without refreshing the page.

Autosuggest is another feature that search engines like Google, Yahoo, or


eCommerce sites like Amazon, BookMyShow, and Uber use. It is because of Ajax
that fetches relevant data offering excellent options for users to choose from.

List Ajax features:


Following are some of the important Ajax features:
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

2) What are the advantages of AJAX?

o Quick Response
o Bandwidth utilization
o The user is not blocked until data is retrieved from the server.
o It allows us to send only important data to the server.
o It makes the application interactive and faster.
3) What are the disadvantages of AJAX?

o Dependent on JavaScript
o Security issues
o Debugging is difficult

4) What are the real web applications of AJAX currently running in


the market?

o Twitter
o Face book
o Gmail
o Javatpoint
o Youtube

5) What are the security issues with AJAX?

o AJAX source code is readable


o Attackers can insert the script into the system

6) What are the applications of Ajax ?


7) What are the technologies used by AJAX?

o HTML/XHTML and CSS - These technologies are used for displaying content
and style.
o DOM - It is used for dynamic display and interaction with data.
o XML - It is used for carrying data to and from server
o XMLHttpRequest - It is used for asynchronous communication between client
and server.
o JavaScript - It is used mainly for client-side validation

8) What is the purpose of XMLHttpRequest? or

What is XMLHttpRequest Object?


Answer:

o It sends data in the background to the server.


o It requests data from the server.
o It receives data from the server.
o It updates data without reloading the page.

The keystone of AJAX is the XMLHttpRequest object.

1. Create an XMLHttpRequest object


2. Define a callback function
3. Open the XMLHttpRequest object
4. Send a Request to a server

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server
behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-
in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Define a Callback Function


A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the
response is ready.

xhttp.onload = function() {
// What to do when the response is ready
}

Send a Request
To send a request to a server, you can use the open() and send() methods of
the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

9) What are the properties of XMLHttpRequest?


The important properties of the XMLHttpRequest object are given below.

o onReadyStateChange - It is called whenever readystate attribute changes.


o readyState - It represents the state of the request.
o responseText - It returns response as text.
o responseXML - It returns response as XML.
o status - It returns the status number of a request.
o statusText - It returns the details of status.
10) What are the important methods of XMLHttpRequest?

o abort() - It is used to cancel the current request.


o getAllResponseHeaders() - It returns the header details.
o getResponseHeader() - It returns the specific header details.
o open() - It is used to open the request.
o send() - It is used to send the request.
o setRequestHeader() - It adds request header.

11) What are the types of open() method used for


XMLHttpRequest?

o open(method, URL) - It opens the request specifying get or post method and
URL.
o open(method, URL, async) - It is same as above but specifies asynchronous or
not.
o open(method, URL, async, username, password) - It is same as above but
specifies the username and password.

..

12) What are the types of send() method used for


XMLHttpRequest?

o send() - It sends get request


o send(string) - It sends post request.

..

13) What is the role of the callback function in AJAX?


The callback function passes a function as a parameter to another function. If we have to perform
various AJAX tasks on a website, then we can create one function for executing
XMLHttpRequest and a callback function to execute each AJAX task.
15) What are the tools for debugging AJAX applications?
There are several tools for debugging AJAX applications.

o Firebug for Mozilla Firefox


o Fiddler for IE (Internet Explorer)
o JavaScript HTML Debugger
o MyEclipse AJAX Tools
o Script Debugger

17) What are the different ready states of a request in AJAX?


There are 5 ready states of a request in AJAX.

o 0 means UNOPENED
o 1 means OPENED
o 2 means HEADERS_RECEIVED
o 3 means LOADING
o 4 means DONE

18) What are the common AJAX frameworks?

o Dojo Toolkit
o YUI
o Google Web Toolkit (GWT)
o Spry
o MooTools
o Prototype

19) How can you test the AJAX code?


JUnit is the open source unit testing framework for client-side JavaScript. It is required to create
test cases. The unit test case is a code which ensures that the program logic works as expected.

20) What is the difference between JavaScript and AJAX?

JavaScript is an object-based AJAX is a group of inter-related technologies


scripting language. like JavaScript, XML, HTML, CSS etc

It requests the server and waits It sends a request to the server and doesn't
for the response. wait for the response.

It consumes more bandwidth It doesn't reload the page so consumes less


as it reloads the page. bandwidth.

22) Describe events and their types in Ajax

Answer: When the user or browser interacts with HTML elements, it is termed an
event.
Some examples of events are:
 onchange – When elements are changed like the text is changed or inserted
into the text field.
 onclick – HTML elements like button, image, link are clicked.
 onload – Loading a page completed by the browser.
 onmouseover – When a user moves the mouse over HTML elements like
image or text.
Ajax events are of two types: Local events and Global events
 Local events – Acts as callbacks inside Ajax request object
Examples: beforeSend, error, complete, success
 Global events – triggered on document and calls listening event handlers
Examples: ajaxSend, ajaxSuccess, ajaxError, ajaxComplete

Ajax events are event handlers and listeners associated with Ajax (Asynchronous JavaScript and
XML) requests. These events play a crucial role in managing the asynchronous nature of web
applications, allowing developers to respond to various stages of an Ajax request's lifecycle. By
handling these events, developers can provide better user feedback, manage errors, and update
the web page dynamically. Here are some common Ajax events and their significance:

1. readystatechange Event:
- Description: The `readystatechange` event is fired when the `readyState` property of the
XMLHttpRequest object changes. The `readyState` property indicates the current state of the
request.
- Significance: This event allows you to track the progress of an Ajax request. The `readyState`
can be used to determine when the request is opened, headers are received, data is being loaded,
and when the request is complete. It's commonly used in conjunction with other events to
manage request progress.

xhr.onreadystatechange = function() {
if (xhr.readyState === 4 &&xhr.status === 200) {
// Request is complete and successful
}
};

2. load Event:
- Description: The `load` event is triggered when the Ajax request has successfully completed,
and the response has been fully received.
- Significance: This event is often used to execute code after a successful request. It's the ideal
point to process and update the web page with the fetched data.
- Example:

xhr.onload = function() {
if (xhr.status === 200) {
// Process and update the web page with the response data
}
};
3. error` Event:
- Description: The `error` event is fired when there's a network error or the server responds
with an error status code (e.g., 404 or 500).
- Significance: This event helps you handle errors gracefully, providing feedback to users when
something goes wrong with the request. Proper error handling is crucial for maintaining a good
user experience.

xhr.onerror = function() {
// Handle network or server errors
};

4. abort Event:
- Description: The `abort` event occurs when the `abort()` method is called on an
XMLHttpRequest object, which cancels the request.
- Significance: This event is useful for handling user-initiated request cancellations. It allows
you to clean up resources or notify the user when a request is intentionally terminated.
- Example:

xhr.onabort = function() {
// Handle the request being aborted
};

These are just a few examples of Ajax events. Other events like `timeout` (triggered when the
request times out), `progress` (used to track the progress of data transfer), and custom events can
be employed based on specific requirements. Ajax events help developers manage the
asynchronous nature of Ajax requests, monitor request status, and provide feedback to users,
making them a critical part of Ajax development.

What is Ajax Response?


This AJAX Ajax.Response is the object passed as the first argument of all Ajax
requests callbacks.

This is a wrapper around the native xmlHttpRequest object. It normalizes cross-


browser issues while adding support for JSON via the responseJSON and
headerJSON properties.

Properties of the Ajax.Response Object

Property Type Description


status Number The HTTP status code sent by the server.
statusText String The HTTP status text sent by the server.
readyState Number The request's current state. 0 corresponds to "Uninitialized", 1 to
"Loading", 2 to "Loaded", 3 to "Interactive" and 4 to "Complete".
responseText String The text body of the response.
responseXML document The XML body of the response if the content-type of the request is set to
Object application/xml. null otherwise.
or null
request Object The request object itself (an instance of Ajax.Request or Ajax.Updater).
transport Object The native xmlHttpRequest object itself.

Q.1) Write a program to use AJAX with PHP. Or example of XMLHttpRequest


Object.

<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "abc.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>

</body>
</html>

Why use Ajax in PHP?


A majority of PHP based sites are using Ajax & jQuery based solutions for
better user experience on their wesites because asynchronous JavaScript
and XML allows for such rich features in the website which PHP alone or
just JavaScript can’t provide us in the website. Some of the features are:

 Search auto suggestions


 Form submitting without page reload

 Content loading on the scroll

So while working with PHP a server side language using Ajax for some
small task will make our lives easy. We don’t need to make multiple pages
and it also provides a better user experience because users have not to
wait for the page to be reloaded again.

One of the best things is that it is very easy to write Ajax code with jQuery
in comparison to the Ajax with JavaScript.

There are many advantages of using Ajax in our web applications,


some of them are mentioned below:

1. Callbacks:

Ajax make a callback in background. It makes possible to communicate


with the server very fast without the page reload.

 Asynchronous:

By using Ajax we can achieve assynchrounous call to website servers. This


method allows the browsers to avoid the waiting period to get the data.

 User-Friendly:

The applications which use Ajax are more faster and responsive to the user
in comparision of others web applications which don’t use Ajax.

Form Submission Using Ajax, PHP and


Javascript
AJAX (Asynchronous JavaScript and XML) is the art of exchanging data
with a server, and updating parts of a web page – without reloading the
whole page.
Now you will learn same functionality using ajax, PHP and Javascript.

For this you must have a database in MY-SQL . Here, we have database named
“mydba” which consists of table named “ ajax_form” with 4-5 fields.

next we create a php page named “ajaxsubmit.php” where following steps were
performed:

 We first establish connection with server .


 Selects database.
 Executes query.
 Closing connection with server.

Index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css
" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<title></title>
</head>
<body>

<div class="container">
<div class="card mt-3">
<div class="card-header">
<center>
<h3>Form Submit using Ajax in PHP MySQL Example</h3>
</center>
</div>
<div>
<form class="p-2" method="post"
action="insert_form_data.php">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control"
placeholder="Name">
</div>
<div class="form-group">
<label>Email address</label>
<input type="email" name="email" class="form-control"
placeholder="Email">
</div>
<button type="submit" class="btn btn-primary"
class="submit">Submit</button>
</form>
</div>
<div class="card-body" id="table">

</div>
</div>
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scri
pt>
<script>
$(document).ready(function(){
function lodetable(){
$.ajax({
url : "table.php",
type : "GET",
success : function(data){
$('#table').html(data);
}
});
}
lodetable();

$('form').on('submit', function (e) {


e.preventDefault();
$.ajax({
type: 'post',
url: 'insert_form_data.php',
data: $('form').serialize(),
success: function () {
alert('Data Inserted Successfully');
lodetable();
$("form").trigger("reset");
}
});
});

});
</script>

</body>
</html>

Insert_form_data.php
<?php

$conn = mysqli_connect("localhost","root","root","form");

$name = $_POST['name'];
$email = $_POST['email'];

$query = "INSERT INTO ajax_form(name,email) VALUES ('$name','$email')";

$result = mysqli_query($conn,$query);

?>
table.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>

<?php
$conn = mysqli_connect("localhost","root","root","form");
$query = "SELECT * FROM ajax_form";
$result = mysqli_query($conn,$query);
?>

<table class="table table-striped">


<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<tr>
<th scope="row"><?php echo $row['id']; ?></th>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

</body>
</html>
What is jQuery?

jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.

The jQuery library contains the following features:

 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities

Downloading jQuery

There are two versions of jQuery available for downloading:

 Production version - this is for your live website because it has been minified and
compressed
 Development version - this is for testing and development (uncompressed and readable
code)

Both versions can be downloaded from jQuery.com.

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-3.7.1.min.js"></script>
</head>
jQuery CDN

If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).

Google is an example of someone who host jQuery:

Google CDN:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

The element Selector

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")
The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the HTML
element:

$("#test")
……………………………………………………………………..
The .class Selector

The jQuery .class selector finds elements with a specific class.

To find elements with a specific class, write a period character, followed by the name of the
class:

$(".test")
……………………………………………………………………………………….

What are Events in jQuery?

All the different visitors' actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

 moving a mouse over an element


 selecting a radio button
 clicking on an element

The term "fires/fired" is often used with events. Example: "The keypress event is fired, the
moment you press a key".

Here are some common DOM events:

Mouse Events Keyboard Events Form Events Document/Window Events


Click Keypress Submit load

Dblclick Keydown Change resize

Mouseenter Keyup Focus scroll

Mouseleave Blur unload

1. AJAX EVENTS PROGRAMMING EXAMPLES :

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>


<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>
2. Ajax Event example program:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

$("#hide").click(function(){
$("p").hide();
});

$("#show").click(function(){
$("p").show();
});

});
</script>
</head>
<body>

<p>BCA - V Sem Sec A</p>


<p>BCA - V Sem Sec B</p>
<p>BCA - V Sem Sec C</p>

<input type='submit' id='hide' value='hide'>


<input type='submit' id='show' value='show'>

</body>
</html>

What is Traversing?

jQuery traversing, which means "move through", are used to "find" (or select) HTML elements
based on their relation to other elements. Start with one selection and move through that
selection until you reach the elements you desire.

jQuery Traversing - Ancestors

With jQuery you can traverse up the DOM tree to find ancestors of an element.

An ancestor is a parent, grandparent, great-grandparent, and so on.


Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:

 parent()
 parents()
 parentsUntil()

Q. Program for traversing jQuery method: parent ()

<!DOCTYPE html>
<html>
<head>
<title>jQuery parent() Function Example</title>
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Wait for the document to be ready
$(document).ready(function() {
// Attach a click event handler to the "Click Me" button
$("#clickMeButton").click(function() {
// Find the parent of the button, which is the <div> element, and
change its background color
$(this).parent().css("background-color", "lightblue");
});
});
</script>
</head>
<body>
<div style="padding: 10px; background-color: lightgray;">
<p>This is a div element.</p>
<button id="clickMeButton">Click Me</button>
</div>
</body>
</html>

jQuery Traversing - Descendants

With jQuery you can traverse down the DOM tree to find descendants of an element.

A descendant is a child, grandchild, great-grandchild, and so on.


Traversing Down the DOM Tree

Two useful jQuery methods for traversing down the DOM tree are:

 children()
 find()

Q. Program for traversing jQuery method: children ()

<!DOCTYPE html>
<html>
<head>

<title>jQuery Traversing - children</title>


<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function () {
// Click event handler for the button
$("#selectChildren").click(function () {
// Use the children method to s"elect the <li> elements within the <ul>
element
$("#parent ul").children().css("color", "red");

});
});
</script>

</head>
<body>
<div id="parent">
<h2>Parent Element</h2>
<ul>
<li>Child 1</li>
<li>Child 2</li>
<li>Child 3</li>
</ul>
</div>

<button id="selectChildren">Select Children</button>


</body>
</html>
Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:

 siblings()
 next()
 nextAll()
 nextUntil()
 prev()
 prevAll()
 prevUntil()

The first(), last(), eq(), filter() and not() Methods

The most basic filtering methods are first(), last() and eq(), which allow you to select a
specific element based on its position in a group of elements.

Other filtering methods, like filter() and not() allow you to select elements that match, or do
not match, a certain criteria.

You might also like