Unit 04 - Introduction to Ajax and JQuery
Unit 04 - 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.
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
o Twitter
o Face book
o Gmail
o Javatpoint
o Youtube
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
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.
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();
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.
..
..
o 0 means UNOPENED
o 1 means OPENED
o 2 means HEADERS_RECEIVED
o 3 means LOADING
o 4 means DONE
o Dojo Toolkit
o YUI
o Google Web Toolkit (GWT)
o Spry
o MooTools
o Prototype
It requests the server and waits It sends a request to the server and doesn't
for the response. wait for the response.
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.
<!DOCTYPE html>
<html>
<body>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "abc.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
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.
1. Callbacks:
Asynchronous:
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.
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:
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();
});
</script>
</body>
</html>
Insert_form_data.php
<?php
$conn = mysqli_connect("localhost","root","root","form");
$name = $_POST['name'];
$email = $_POST['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);
?>
</body>
</html>
What is jQuery?
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.
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX
Utilities
Downloading jQuery
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)
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 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).
Examples:
The jQuery element selector selects elements based on the element name.
$("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
To find elements with a specific class, write a period character, followed by the name of the
class:
$(".test")
……………………………………………………………………………………….
All the different visitors' actions that a web page can respond to are called events.
Examples:
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the
moment you press a key".
<!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>
</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>
</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.
With jQuery you can traverse up the DOM tree to find ancestors of an element.
Three useful jQuery methods for traversing up the DOM tree are:
parent()
parents()
parentsUntil()
<!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>
With jQuery you can traverse down the DOM tree to find descendants of an element.
Two useful jQuery methods for traversing down the DOM tree are:
children()
find()
<!DOCTYPE html>
<html>
<head>
<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>
There are many useful jQuery methods for traversing sideways in the DOM tree:
siblings()
next()
nextAll()
nextUntil()
prev()
prevAll()
prevUntil()
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.