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

MODULE 3

1)Example of usage of AJAX

Simple Examples

A simple AJAX example


Create a simple XMLHttpRequest, and retrieve data from a TXT file.

An AJAX example with a callback function


Create a XMLHttpRequest with a callback function, and retrieve data from a TXT file.

Request Header Information

Retrieve all header information of a resource (file)

Retrieve specific header information of a resource (file)

Request XML Files

Load an XML file with AJAX


Create an XMLHttpRequest to retrieve data from an XML file.

Retrieve the content of an XML file


Create an XMLHttpRequest to retrieve data from an XML file and display the data in an HTML table.

Retrieve Server Data with PHP and ASP

Retrieve the content of a PHP file


How a web page can communicate with a web server while a user type characters in an input field.

Retrieve the content of an ASP file


How a web page can communicate with a web server while a user type characters in an input field.

Retrieve Database Information

Retrieve content from a database


How a web page can fetch information from a database with AJAX.

AJAX Applications

View an XML CD catalog


Display XML data in an HTML table
Show XML data inside an HTML div element
Navigate through XML nodes
A simple CD catalog application
2.Asynchronous communication and Ajax Application model

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.

3.Data download and displaying the fetched data

Fetch and display data from APIs in react js; This tutorial will provide you a complete guide on how to
fetch and display data from APIs in react js.

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP
pipeline, such as requests and responses. It also provides a global fetch() method that provides an
easy, logical way to fetch resources asynchronously across the network.

How to Fetch and Display Data From API in React JS using fetch()

 Step 1 – Create React App


 Step 2 – Install Bootstrap
 Step 3 – Create Listing Component
 Step 3 – Create Listing Component
 Step 4 – Import Listing Component in App.js

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new
react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Bootstrap

In this step, execute the following command to install react boostrap library into your react app:

npm install bootstrap --save

Add bootstrap.min.css file in src/App.js file:

import React, { Component } from 'react'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {

  return (

    <div>

      <h2>How to Display Data From API in React JS using fetch()</h2>

    </div>

  );

export default App;

Step 3 – Create Listing Component

In this step, create listing.js file. So, visit the src directory of your react js app and create a listing
component file named listing .js. And add the following code into it:

import React, { Component } from 'react';

class Listing extends Component {

    constructor(props) {
        super(props)  

        this.state = {

            records: []

        }

    }

    componentDidMount() {

        fetch('https://jsonplaceholder.typicode.com/users')

            .then(response => response.json())

            .then(records => {

                this.setState({

                    records: records

                })

            })

            .catch(error => console.log(error))

    }

    renderListing() {

        let recordList = []

        this.state.records.map(record => {

            return recordList.push(`<li key={record.id}>{record.name}</li>`)

        }) 

        return recordList;

    }

    render() {

        return (

            `<ul>

                {this.renderListing()}

            </ul>`

        );

    }

export default Listing;

The above code uses the fetch API of the browser. It internally uses javascript promises to resolve
the asynchronous response.
Step 4 – Import Listing Component in App.js

In this step, import the listing.js file in src/App.js file:

import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

import Listing from './Listing'

class App extends Component {

  render() {

    return (

      <div className="App">

        <Listing />

      </div>

    );

  }

export default App;

4.Sending data to the server using GET and POST

Get and Post Methods in PHP

PHP provides two methods through which a client (browser) can send information to the server.
These methods are given below, and discussed in detail:

1. GET method
2. POST method

Get and Post methods are the HTTP request methods used inside the <form> tag to send form data
to the server.

HTTP protocol enables the communication between the client and the server where a browser can be
the client, and an application running on a computer system that hosts your website can be the
server.

GET method

The GET method is used to submit the HTML form data. This data is collected by the


predefined $_GET variable for processing.
The information sent from an HTML form using the GET method is visible to everyone in the
browser's address bar, which means that all the variable names and their values will be displayed in
the URL. Therefore, the get method is not secured to send sensitive information.

For Example

1. localhost/gettest.php?username=Harry&bloodgroup=AB+  

The bold part in the above URL is the variables name and italic part contains the values for their
corresponding variable.

Note that only a limited amount of information can be sent using the GET method.

With the help of an example, let's understand how the GET method works-

Example

The below code will display an HTML form containing two input fields and a submit button. In this
HTML form, we used the method = "get" to submit the form data.

file: test1.html

1. <html>  
2.    <body>  
3.      
4.       <form action = "gettest.php" method = "GET">  
5.          Username: <input type = "text" name = "username" /> <br>  
6.          Blood Group: <input type = "text" name = "bloodgroup" /> <br>  
7.          <input type = "submit" />  
8.       </form>  
9.         
10.    </body>  
11. </html>  

Create gettest.php file, which will accept the data sent by HTML form.

file: gettest.php
1. <html>  
2.    <body>  
3.      
4.       Welcome <?php echo $_GET["username"]; ?> </br>  
5.       Your blood group is: <?php echo $_GET["bloodgroup"]; ?>  
6.   
7.    </body>  
8. </html>  

When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:

localhost/gettest.php?username=Harry&bloodgroup=AB-

The output will look like the below output:

Welcome Harry
Your blood group is: AB-

Advantages of GET method (method = "get")

o You can bookmark the page with the specific query string because the data sent by the GET
method is displayed in URL.
o GET requests can be cached.
o GET requests are always remained in the browser history.

Disadvantages of GET Method

o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed 2048
characters.
o For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.
o The GET method cannot be used to send binary data (such as images or word documents) to
the server.

POST method

Similar to the GET method, the POST method is also used to submit the HTML form data. But the
data submitted by this method is collected by the predefined superglobal variable $_POST instead of
$_GET.

Unlike the GET method, it does not have a limit on the amount of information to be sent. The
information sent from an HTML form using the POST method is not visible to anyone.
For Example

1. localhost/posttest.php  
Note that the "post" method is more secure than the "get" method because the data sent using the
POST method is not visible to user.

With the help of an example, let's understand how the POST method works-

Example

The below code will display an HTML form containing two input fields and a submit button. In this
HTML form, we used the method = "post" to submit the form data.

file: test2.html

1. <html>  
2.    <body>  
3.      
4.       <form action = "posttest.php" method = "post">  
5.          Username: <input type = "text" name = "username" /> <br>  
6.          Blood Group: <input type = "text" name = "bloodgroup" /> <br>  
7.          <input type = "submit" />  
8.       </form>  
9.         
10.    </body>  
11. </html>  

Now create posttest.php file to accept the data sent by HTML form.

file: posttest.php

1. <html>  
2.    <body>  
3.      
4.       Welcome <?php echo $_POST["username"]; ?> </br>  
5.       Your blood group is: <?php echo $_POST["bloodgroup"]; ?>  
6.    </body>  
7. </html>  

When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:

localhost/posttest.php

The output will look like the below output:

Welcome Harry
Your blood group is: O+

Advantages of POST method (method = "post")

o The POST method is useful for sending any sensitive information because the information sent
using the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a large
amount of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the POST
method goes through the HTTP header. By using secure HTTP, you can ensure that your data
is safe.

Disadvantages of POST Method

o POST requests do not cache.


o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.

$_REQUEST variable

The $_REQUEST variable is a superglobal variable, which can hold the content of both $_GET and
$_POST variable. In other words, the PHP $_REQUEST variable is used to collect the form data sent
by either GET or POST methods. It can also collect the data for $_COOKIE variable because it is not
a method-specific variable.
Module 4

1.Using two XMLHttpRequest objects

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();

Example
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();

// Define a callback function


xhttp.onload = function() {
  // Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same
server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you load must be
located on your own server.

XMLHttpRequest Object Methods

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method, url, async, user, psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password
send() Sends the request to the server
Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

Property Description

Onload Defines a function to be called when the request is


recieved (loaded)

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"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")


The onload Property

With the XMLHttpRequest object you can define a callback function to be executed when the request
receives an answer.

The function is defined in the onload property of the XMLHttpRequest object:

Example
xhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Multiple Callback Functions

If you have more than one AJAX task in a website, you should create one function for executing
the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is ready.

Example
loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {cFunction(this);}
  xhttp.open("GET", url);
  xhttp.send();
}

function myFunction1(xhttp) {
  // action goes here
}
function myFunction2(xhttp) {
  // action goes here
}

The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a callback function to be executed when the readyState


changes.

The status property and the statusText properties hold the status of the XMLHttpRequest object.


Property Description

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

Status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt");
  xhttp.send();
}

2.Short Notes

a.multistage download

While establishing asynchronous communication, a set of patterns are followed to make the process
more efficient. One such design pattern is Multistage Downloading.
Until now, some action of the user (like click) has triggered the process of fetching the response. This
includes a small wait period from the user’s side until it is fetched. But in certain cases this can be
annoying. The goal is to automatically fetch data without the user having to ask for it.

Multistage Downloading is necessary when a huge amount of data needs to be downloaded. The
order in which this download occurs is very crucial. The most relevant and light data must arrive first
so that the user can get started. The heaviest ones should probably arrive later. The advantage of
this approach is that, if the user navigates away from the page fairly quickly, then the heavy
downloads are avoided.

This process should include indicators ( like progress bars) to inform the user that more data is
arriving. It should also have place holders which can accept this arriving data easily.

We will now look at an example where the webpage first loads some text content. And then based on
whether the user stays on the page, it goes on to download the images.

1 <body onload="init()">
2  ....
3 </body>
The init method will setup the async communication using XMLHttp and fetch the text data
from content.txt.
1 var xhr=new XMLHttpRequest();
2 function init(){
3   xhr.onreadystatechange=showContent;
4   xhr.open("GET","content.txt",true);
5   xhr.send();
6 }
Advertisements
REPORT THIS AD
Now let us assume that the data returned by the server has some text data and a loading icon.
The showContent method will fill the text fields and will display this loading icon.
1 function showContent(){
2   if(xhr.readyState==4 && xhr.status==200){
3       var res=xhr.responseText;
4       var resArr=res.split(";");
5       document.getElementById("text_field").innerHTML=resArr[0];
6  
7       // display a loading icon
8       document.getElementById("picture").innerHTML=resArr[1];
9  
10       setTimeout(getPic,4000);
11    }
12 }
The setTimeout(getPic,4000) at the end signifies that if the user stays for 4 seconds on this page then
the getPic function will be called. Now the getPic method will also establish an asynchronous
communication channel, but this time with the image source.
1 function getPic(){
2   this.xhr.onreadystatechange=this.showPic;
3   this.xhr.open("GET","img.txt",true);
4   this.xhr.send();
5 }
6 function showPic(){
7   if(xhr.readyState==4 && xhr.status==200){
8     var res=this.responseText;
9     document.getElementById("picture").innerHTML=res;
10   }
11 }
The advantage of using Multistage Downloading is that the developer now decides what gets
download and when.

But the disadvantages are :

1. For browsers that don’t support AJAX techniques, the page must work in its simplest form.

2. The basic functionality of the page must work without any additional downloads.

b.PeriodicRefresh
Periodic Refresh fakes a back-channel: it approximates a situation where the server pushes data to
the client, so the server can effectively receive new information from the browser. Indeed, as some of
the examples show, the server can also mediate between users in almost real-time. So Periodic
Refresh can be used for peer-to-peer communication too.

But before we get too carried away with Periodic Refresh, it's important to note that it's a serious
compromise, for two key reasons:

o The period between refreshes would ideally be zero, meaning instant updates. But that's not
realistic and the browser will always lag behind. Latency is particularly problematic when the
user is interacting with a representation of volatile server-side data. For instance, a user might
be editing an object without knowing that another user has already deleted it.

o There is a significant cost attached to Periodic Refresh. Each request, no matter how tiny,
demands resources at both ends, all the way down to operating-system level. Traffic-wise,
each request also entails some bandwidth cost, which can add up if refreshes are occurring
once every few seconds.

So a key design objective must be to increase the average refresh period and reduce the content per
refresh, while maintaining a happy user experience. One optimization is a timeout: the refreshes
cease when the system detects the user is no longer active, according to a Timeout (Chapter 17)
mechanism. You also want to make sure each refresh counts; it's wasteful to demand lots of updates
if the network isn't capable of delivering them. Thus, the browser script can do some monitoring and
dynamically adjust the period so it's at least long enough to cope with all incoming updates. Many of
the Performance Optimization patterns can also be applied to Periodic Refreshsee the next section.

c.Submission Throttling

 Submission throttling solves the issue of when to send user data to the server.
 In a traditional web site or web application, each click makes a request back to the server so
that the server is always aware of what the client is doing.
 In the Ajax model, the user interacts with the site or application without additional requests
being generated for each click.
 In a traditional web solution data send back to the server every time when user action occurs.
Thus, when the user types a letter, that letter is sent to the server immediately. The process is
then repeated for each letter typed.
 The problem with this approach is that it has the possibility to create a large number of
requests in a short amount of time, which may not only cause problems for the server but may
cause the user interface to slow down as each request is being made and processed.
 The Submission Throttling design pattern is an alternative approach to solve this problematic
issue.
 Using Submission Throttling, you buffer the data to be sent to the server on the client and then
send the data at predetermined times.
o Submission Throttling typically begins either when the web site or application first loads
or because of a specific user action.
o Then, a client-side function is called to begin the buffering of data.
o Every so often, the user's status is checked to see if user is idle or not. If the user is still
active, data continues to be collected.
o When the user is idle, means not performing any action, it's time to decide whether to
send the data. This determination varies such as, data is send only when it reaches a
certain size, or data is sending every time when the user is idle.
o After the data is sent, the application typically continues to gather data until either a
server response or some user action signals to stop the data collection.
 Example: Google Suggest feature does this brilliantly. It doesn't send a request after each
character is typed. Instead, it waits for a certain amount of time and sends all the text currently
in the text box. The delay from typing to sending has been fine-tuned to the point that it doesn't
seem like much of a delay at all. Submission Throttling, in part, gives Google Suggest its
speed.

d.Predictive Fetch

 The Predictive Fetch pattern is a relatively simple idea that can be somewhat difficult to
implement: the Ajax application guesses what the user is going to do next and retrieves the
appropriate data.
 In a perfect world, it would be wonderful to always know what the user is going to do and make
sure that the next data is readily available when needed. In reality, however, determining future
user action is just a guessing game depending on user’s intentions.
 Suppose user is reading an online article that is separated into three pages. It is logical to
assume that if user is interested in reading the first page, then user also interested in reading
the second and third page.
 So if the first page has been loaded for a few seconds (which can easily be determined by
using a timeout), it is probably safe to download the second page in the background. Likewise,
if the second page has been loaded for a few seconds, it is logical to assume that the reader
will continue on to the third page.
 As this extra data is being loaded and cached on the client, the reader continues to read and
barely even notices that the next page comes up almost instantaneously after clicking the Next
Page link.
 Example: This approach is taken by many web-based e-mail systems,
including Gmail and AOL Webmail; During the writing of an e-mail, its general e-mail is for
someone whom user knows, so it's logical to assume that the person is already in user's
address book. To help out user, it may be wise to pre-load user's address book in the
background and offer suggestions.

e.Fallback Patterns

 We pre-suppose that everything goes according to plan on the server-side: the request is
received, the necessary changes are made, and the appropriate response is sent to the client.
But what happens if there's an error on the server? Or worse yet, what if the request never
makes it to the server?
 When developing Ajax applications, it is imperative that you plan ahead for these problems
and describe how your application should work if one of these should occur.

Cancel Pending Requests

 If an error occurs on the server, meaning a status of something other than 200 is returned, you
need to decide what to do. Chances are that if a file is not found (404) or an internal server
error occurred (302), trying again in a few minutes isn't going to help since both of these
require an administrator to fix the problem.
 The simplest way to deal with this situation is to simply cancel all pending requests. You can
set a flag somewhere in your code that says, "don't send any more requests."
 This solution has maximum impact on the Periodic Refresh Pattern.

Try Again

 Another option when dealing with errors is to silently keep trying for either a specified amount
of time or a particular number of tries.
 Once again, unless the Ajax functionality is key to the user's experience, there is no need to
notify user about the failure. It is best to handle the problems behind the scenes until it can be
resolved.
 In general, the Try Again pattern should be used only when the request is intended to occur
only once, as in a Multi-Stage Download.

You might also like