Ajax

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Ajax Introduction

Introduction:
The following tutorial will provide a short introduction to Ajax and its uses.
Before understanding these terms see few practical examples to
demonstrate the power of Ajax. Facebook, Instagram, Twitter etc are
considered the situation when check news feed and if like someone post
simply click the like button and the like count is added without refreshing the
page. Now imagine the situation if there would be the case, click the like
button and the complete page would be loaded again which will make such
processes. Now the question whether clicking the button again for such a
small task which require complete loading of a web page. Absolutely not,
because no one will do such an absurd thing (in the latter case). So it means
that this feature of like is very helpful as it prevents the reloading of the
complete page. It communicates only necessary information with the server
and shows to the end user(in this case being the increase of like count).
Consider another case when visit google to search for anything. Usually,
observe that when start typing the desired keywords to search, observe that
many suggestions are presented in the search bar. Now, where do they
come from? Of course not from the client side. The results are again the
power of communication with the server without reloading the page again.
Like this, there are dozens of examples which can be considered. The whole
power working behind is nothing but Ajax. Let’s discuss briefly Ajax and its
implementation.
What is Ajax?
Ajax is an acronym for Asynchronous Javascript and XML. It is used to
communicate with the server without refreshing the web page and thus
increasing the user experience and better performance.
Prerequisites:
There are no such pre-requisites required to understand the latter portion of
the article. Only the basic knowledge of HTML, CSS, and JavaScript are
good to go.
How does it work?
First, let us understand what does asynchronous actually mean. There are
two types of requests synchronous as well as asynchronous. Synchronous
requests are the one which follows sequentially i.e if one process is going on
and in the same time another process wants to be executed, it will not be
allowed that means the only one process at a time will be executed. This is
not good because in this type most of the time CPU remains idle such as
during I/O operation in the process which are the order of magnitude slower
than the CPU processing the instructions. Thus to make the full utilization of
the CPU and other resources use asynchronous calls. For more information
visit this link. Why the word javascript is present here. Actually, the requests
are made through the use of javascript functions. Now the term XML which is
used to create XMLHttpRequest object.
Thus the summary of the above explanation is that Ajax allows web pages to
be updated asynchronously by exchanging small amounts of data with the
server behind the scenes. Now discuss the important part and its
implementation. For implementing Ajax, only be aware of XMLHttpRequest
object. Now, what actually it is. It is an object used to exchange data with
the server behind the scenes. Try to remember the paradigm of OOP
which says that object communicates through calling methods (or in general
sense message passing). The same case applied here as well. Usually,
create this object and use it to call the methods which result in effective
communication. All modern browsers support the XMLHttpRequest object.
Basic Syntax: The syntax of creating the object is given below

req = newXMLHttpRequest();

There are two types of methods open() and send(). Uses of these methods
explained below.

req.open("GET", "abc.php", true);

req.send();

The above two lines described the two methods. req stands for the request,
it is basically a reference variable. The GET parameter is as usual one of two
types of methods to send the request. Use POST as well depending upon
whether send the data through POST or GET method. The second
parameter being the name of the file which actually handles the requests and
processes them. The third parameter is true, it tells that whether the requests
are processed asynchronously or synchronously. It is by default true which
means that requests are asynchronous. The open() method prepares the
request before sending it to the server. The send method is used to send the
request to the server.
Sending the parameter through getting or POST request. The syntax is given
below

req.open("GET", "abc.php?x=25", true);

req.send();

In the above lines of code, the specified query in the form of URL followed by
?which is further followed by the name of the variable then = and then the
corresponding value. If sending two or more variables use ampersand(&)
sign between the two variables. The above method as shown applies for
GET request. Sending the data through the POST, then send it in the send
method as shown below.

req.send("name=johndoe&marks=99");

.
Use of setRequestHeader() method as shown below.

req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

Events and handling mechanism:


Any action performs on the clicking button, hovering over elements, page
loading etc all are termed as events. Also aware of fact that javascript can
detect events. So bind the code of specific event with its action which can be
implemented by javascript. These are basically event handlers.
Implementing event handlers which actually hold the events. Events handlers
are basically functions written in javascript which act on or set into action
when an event is fired by the user. When sending the request through send
method usually get the response from the server later. But getting of
response time is not known. So track it.
Therefore to keep a track of the response onreadystatechange event which
is binding with the event handler(function) which will get executed when a
response comes.
When a request to the server is sending perform actions based on the
response. The onreadystatechange event is triggered every time the
readyState changes. So what actually a ready state is and when will the
onreadystate event actually occur and how many times it will occur between
the request and response?
The XMLHttpRequest object has a property called as readyState whose
value changes in the complete request-response journey i.e when a request
is prepared, sent, resolves, processed and when the response comes. That’s
why it is called osonreadystatechange.
The onreadystatechange stores a function (or the name of the function)to be
called automatically each time the readyState property changes.
The readyState holds different values ranging from 0 to 4.
1. request not initialized
2. server connection established
3. request received
4. processing request
5. request finished and response is ready
XMLHttpRequest also has a property named as status. The status has
following values
 200: “OK”
 404: “Page not found”
Now remember it always that when readyState is 4 and status is 200, the
response is ready.
The whole thing described above is implemented in coding as given below

<p id = "dis">< /p>

req.onreadystatechange = function(){

  if(req.readyState == 4 &&req.status == 200){

      document.getElementById("dis").innerHTML = req.responseText;

  }

(Note: This is only a section of code and moreover describing the


communication between client and server so the code described above will
not show any effect if run on IDE)
In the above code if the condition is true (i.e the response is ready) then the
result is displayed.
Advantages:
1. Speed is enhanced as there is no need to reload the page again.
2. AJAX make asynchronous calls to a web server, this means client
browsers avoid waiting for all the data to arrive before starting of
rendering.
3. Form validation can be done successfully through it.
4. Bandwidth utilization – It saves memory when the data is fetched from the
same page.
5. More interactive.
Disadvantages:
1. Ajax is dependent on Javascript. If there is some Javascript problem with
the browser or in the OS, Ajax will not support.
2. Ajax can be problematic in Search engines as it uses Javascript for most
of its parts.
3. Source code written in AJAX is easily human readable. There will be
some security issues in Ajax.
4. Debugging is difficult.
5. Problem with browser back button when using AJAX enabled pages.
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.

Why to Learn Ajax?


AJAX stands for Asynchronous JavaScript and XML. 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. In the purest sense, the
user would never know that anything was even transmitted to the server.
 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.
 A user can continue to use the application while the client program requests
information from the server in the background.
 Intuitive and natural user interaction. Clicking is not required, mouse
movement is a sufficient event trigger.
 Data-driven as opposed to page-driven.

Rich Internet Application Technology


AJAX is the most viable Rich Internet Application (RIA) technology so far. It is getting
tremendous industry momentum and several tool kit and frameworks are emerging.
But at the same time, AJAX has browser incompatibility and it is supported by
JavaScript, which is hard to maintain and debug.

AJAX is Based on Open Standards


AJAX is based on the following open standards −

 Browser-based presentation using HTML and Cascading Style Sheets (CSS).


 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the
browser.
 JavaScript to make everything happen.

AJAX cannot work independently. It is used in combination with other technologies to


create interactive webpages.
JavaScript
 Loosely typed scripting language.
 JavaScript function is called when an event occurs in a page.
 Glue for the whole AJAX operation.

DOM
 API for accessing and manipulating structured documents.
 Represents the structure of XML and HTML documents.

CSS
 Allows for a clear separation of the presentation style from the content and
may be changed programmatically by JavaScript

XMLHttpRequest
 JavaScript object that performs asynchronous interaction with the server.
Here is a list of some famous web applications that make use of AJAX.

Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a button.
 https://maps.google.com/

Google Suggest
As you type, Google offers suggestions. Use the arrow keys to navigate the results.
 https://www.google.com/webhp?complete=1&hl=en

Gmail
Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and
useful.
 https://gmail.com/

Yahoo Maps (new)


Now it's even easier and more fun to get where you're going!
 https://maps.yahoo.com/
Difference between AJAX and Conventional CGI Program
Try these two examples one by one and you will feel the difference. While trying
AJAX example, there is no discontinuity and you get the response very quickly, but
when you try the standard GCI example, you would have to wait for the response
and your page also gets refreshed.
AJAX Example
AJAX
 *   =   

Standard Example
Standard
 *   =   
NOTE − We have given a more complex example in AJAX Database.

Steps of AJAX Operation


 A client event occurs.
 An XMLHttpRequest object is created.
 The XMLHttpRequest object is configured.
 The XMLHttpRequest object makes an asynchronous request to the
Webserver.
 The Webserver returns the result containing XML document.
 The XMLHttpRequest object calls the callback() function and processes the
result.
 The HTML DOM is updated.
Let us take these steps one by one.

A Client Event Occurs


 A JavaScript function is called as the result of an event.
 Example − validateUserId() JavaScript function is mapped as an event handler
to an onkeyup event on input form field whose id is set to "userid"
 <input type = "text" size = "20" id = "userid" name = "id" onkeyup =
"validateUserId();">.

The XMLHttpRequest Object is Created


varajaxRequest;// The variable that makes Ajax possible!
functionajaxFunction(){
try{
What is AJAX?
AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX 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 a misleading name. AJAX applications might use XML to transport


data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging 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.

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 keystone of AJAX is the XMLHttpRequest object.

 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.

 Create an XMLHttpRequest Object


 All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari,
Opera) have a built-in XMLHttpRequest object.
 Syntax for creating an XMLHttpRequest object:
 variable = new XMLHttpRequest();

 Example
 var xhttp = new XMLHttpRequest();
 Try it Yourself »

 <!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() {

 varxhttp = new XMLHttpRequest();

 xhttp.onreadystatechange = function() {

 if (this.readyState == 4 &&this.status == 200) {

 document.getElementById("demo").innerHTML = this.responseText;

 }

 };

 xhttp.open("GET", "ajax_info.txt", true);

 xhttp.send();

 }

 </script>

 </body>

 </html>

Output:

The XMLHttpRequest Object


Let AJAX change this text.

Change Content
 The "ajax_info.txt" file used in the example above, is a simple text file
and looks like this:

 <h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web
page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

JavaScript Vs. Angular Js


JavaScript is a lightweight, object-oriented scripting language used to build dynamic
HTML pages with interactive effects on a web page that runs in the client's web
browser. It's a client-side scripting language that provides interactive effects to web
pages to make them more dynamic. On the other hand, Angular JS is a JavaScript-
based framework that extends HTML with new features. It is mainly designed to
develop dynamic and single-page web applications (SPAs). In this article, we are
going to discuss the difference between JavaScript and Angular JS. But before
discussing the differences, we will know about JavaScript and Angular JS.

What is JavaScript?
JavaScript is a lightweight, object-oriented scripting language that is used to
build dynamic HTML pages with interactive effects on a webpage. JavaScript is also
commonly used in game development and mobile app development. It is an
interpreted scripting language, and its code is only executed in a web browser. We
may use Node.js to run the code outside the browser. It's also known as a browser's
language. It can be used for both client-side and server-side development. Brendan
Eich of Netscape created it, and it was first published in 1995. The language was
originally known as LiveScript before being renamed JavaScript. JavaScript's syntax
is heavily influenced by the programming language C. The extension of JavaScript
filename is .js.

JavaScript Features
There are various features of JavaScript. Some of them are as follows:

o JavaScript was originally designed for DOM manipulation. Earlier, most websites were
static, but with JS, an interactive Web site can be developed.
o Functions are objects in JavaScript. They may have the same properties and methods
as other objects and passed as arguments to other functions.
o JavaScript doesn't need a compiler.
o JavaScript may handle date and time.

What is Angular Js?


It is an open-source and front-end web development framework with great features
or support. Google's Angular team first launched it in 2010. It is a framework that is
continually developing and expanding to include better methods for creating web
applications. It develops applications primarily using the model view controller
(MVC) concept and supports both data binding features and dependency injection.

Play Videox

Since AngularJS is mainly based on HTML and JavaScript, there is no need to learn


another syntax or language. It transforms static HTML into dynamic HTML. It extends
HTML's capabilities by adding built-in attributes and components and creating
custom attributes using simple JavaScript.

Angular JS features
There are various features of angular JS. Some of them are as follows:

o Time-saving: AngularJS allows us to work with modules that help us to reuse them,


saving time and code.
o Easy to work: It is easy to work with Angular JS because it uses JavaScript, HTML,
and CSS languages.
o Ready to use a template: AngularJS is mostly plain HTML, and it mostly uses the
plain HTML template, which it passes to the DOM and then to the AngularJS
compiler. It passes through the templates, and then they're ready to use.

Main differences between the JavaScript and Angular


JS
There are various main differences between JavaScript and Angular JS. Some of them
are as follows:

o JavaScript is both a server-side and client-side scripting language for building web
applications. On the other hand, AngularJS makes web applications quick and
straightforward from the start.
o JavaScript takes less time to patch bugs and defects on a wide scale. As compared to
JavaScript, AngularJS needs more time to do the same thing.
o JavaScript is one of the most effective web development techniques used for creating
web applications. On the other hand, AngularJS has mostly been used as a JS
framework for developing web applications.
o JavaScript is a programming language that is used to manipulate
the DOM (Document Object Model). On the other hand, AngularJS extends its
capabilities with different technologies.
o JavaScript doesn't support dependency injection. Whereas AngularJS supports both
data binding and dependency injection.
o JavaScript code is quick and fast. On the other hand, Angular JS application generally
becomes slow.
o JavaScript has been using the same strategy for several years. On the other hand,
AngularJS has been enhanced to typescript, making the applications lighter and more
interactive.
o JavaScript has an extensive user interface that includes sliders and other features. On
the other hand, AngularJS is a data-driven framework that's used to create web
applications.
o JavaScript is a powerful and complex programming language. On the other hand,
AngularJS is a simple and effective framework.
Head-to-Head comparison between JavaScript and
Angular JS
Here, we are going to discuss a head-to-head comparison between JavaScript and
Angular JS:

Features JavaScript Angular JS

Definition It is an object-oriented scripted It an open-source framework used


language that is used to develop to develop dynamic web and large
mobile and dynamic web single-page web applications.
applications.

Developed Netscape Communications Google mainly developed it in


developed it in 1995. 2010.

Syntax Its syntax is much complex than Its syntax is simple and easy.
Angular JS.

Programme Its interpreters are written in the C It is written in the JavaScript


d and C++ languages. language.

Filters It doesn't support the filters. It does support filters.

Learnability It isn't very easy to learn. It is easy to learn if anyone knows


the basic knowledge of JavaScript.

Concept It is based on the dynamic typing Angular JS is based on the concept


concept. of the model view controller to
build the applications.

Dependenc It doesn't support the dependency It supports both data binding and
y injection injection. dependency injection.

Conclusion
Both of these web technologies are used to create web applications. JavaScript is an
open-source and object-oriented programming language, while AngularJS is an
open-source framework based on the MVC model. JavaScript is a programming
language for web creation that enhances website interactivity. It helps to manipulate
the content on websites to verify user feedback at the browser end, thus influencing
the user action by including dynamic content like drag and drop elements, sliders,
and many others. It's one of the World Wide Web's three core technologies and the
foundation for all JavaScript technologies.

On the other hand, Angular JS is an open-source framework that specializes in


developing massive single-page applications and is written in JavaScript. It is based
on the MVC architecture. It is a data-driven approach that enables web applications
to have a larger HTML library. It is a framework for the future to meet large data
requirements without having to refresh Models.

You might also like