Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit - 7 Advanced Web Programming Concepts

AWD

Uploaded by

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

Unit - 7 Advanced Web Programming Concepts

AWD

Uploaded by

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

Unit 7

Advanced Web Programming concepts


Asynchronous Web Programming
• Asynchronous programming allows you to offload work. That way you can
perform that work without blocking the main process/thread (for instance
navigation and utilization of the app). It’s often related to parallelization, the
art of performing independent tasks in parallel, that is achieved by using
asynchronous programming.

• With parallelization, you can break what is normally processed sequentially,


meaning break it into smaller pieces that can run independently and
simultaneously.

• Parallelization is not just related to processes and capabilities but also with the
way systems and software are designed.

• The biggest advantage of applying parallelization principles is that you can


achieve the outcomes much faster and it makes your system easier to evolve
and more resilient to failure.
Difference between synchronous and
asynchronous web programming
• In synchronous operations tasks are performed one at a time and only when one
is completed, the following is unblocked. In other words, you need to wait for a
task to finish to move to the next one.

• In asynchronous operations, on the other hand, you can move to another task
before the previous one finishes. This way, with asynchronous programming
you’re able to deal with multiple requests simultaneously, thus completing more
tasks in a much shorter period of time.
Difference between synchronous and
asynchronous web programming
When to Use Asynchronous Programming

• Asynchronous execution is not the best scenario for all use cases. We should only
use it if you’re dealing with independent tasks. So, when you’re designing a
system, the first step you need to take is to identify the dependencies between
processes and define which you can execute independently and which needs to
be executed as a consequence of other processes.

• In Previous image. On the top, you can see that in synchronous execution, the
tasks are executed in a sequential way; the products are the first to be executed,
then customers, and finally orders.
Difference between synchronous and
asynchronous web programming
When to Use Asynchronous Programming

• Now imagine that we did an analysis and concluded that customers are
independent of products, and vice-versa, but that to execute orders you need the
information from products first—there’s a dependency. In that case, the first two
tasks can be executed asynchronously, but orders will only be executed when
products are completed—so, synchronously.

• As a result, by applying parallel computing and asynchronous programming


when dealing with independent tasks, you’re able to perform these tasks way
faster than with synchronous execution because they’re executed at the same
time. This way, your system releases valuable resources earlier and it’s ready to
execute other processes that queued.
Difference between synchronous and
asynchronous web programming
How to Design a System that Runs Asynchronously

• To better illustrate how to design a system that follows asynchronous


programming principles, let’s try to do it using a typical claims processing portal.
Something like this (Figure Next Slide)

• In this challenge, we have the portal that policyholders or other entities use to
insert and manage claim information.

• This portal communicates with a claims validation system through an API. The
validation system imports data to a business validation engine that includes a
broker and business rules that are processes and logic agnostic to external
systems.

• Finally, this system integrates with payment channels to which it exports the
outcomes of the business validation.
https://www.outsystems.com/blog/posts/asynchronous-vs-synchronous-programming/
Difference between synchronous and
asynchronous web programming
Here are the main key points:

• Use the asynchronous techniques that are more suitable for the outcome.

• Scale front-end servers and configurations to fit your needs. Keep in mind that
when you go into millions of records, you need more front-end servers to
accomplish your needs.

• Design with flexibility in mind and avoid hard coded values or site properties.
Imagine you use hard coded values for bucket control; if your claims validation
process becomes slower and for some reason you’re not aware, you start having
timeouts. Now you’re in an even worse situation, because you need to publish the
changes and not go into a backoffice to change it.

• Don’t over engineer. Try to keep your architecture and system as simple as
AJAX
• Before understanding AJAX, let’s understand classic web application model and
ajax web application model first.

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.

• As we can see in the above image, full page is refreshed at request time and user
is blocked until request completes.
AJAX
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.

• As we can see in the above image, full page is not refreshed at request time and
user gets response from the ajax engine.
AJAX
• 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.
AJAX
• 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.


AJAX
• 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 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
• 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.
AJAX
• 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/
AJAX
• AJAX Example
<!DOCTYPE html>

<html>

<body>

<div id="demo">

<h2>Let AJAX change this text</h2>

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

</div>

</body>

</html>
AJAX
• AJAX Example
Function loadDoc()

function loadDoc() {

var 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", true);

xhttp.send();

}
AJAX
• 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.
AJAX
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
AJAX
AJAX - The XMLHttpRequest Object

• 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 web server
behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
AJAX
AJAX - The XMLHttpRequest Object

Create an XMLHttpRequest Object

• All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in
XMLHttpRequest object.

• Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest(); - example

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.

• 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.
AJAX
AJAX - The XMLHttpRequest Object

Create an XMLHttpRequest Object

Modern Browsers (Fetch API)

• Modern Browsers can use Fetch API instead of the XMLHttpRequest Object.

• The Fetch API interface allows web browser to make HTTP requests to web
servers.

• If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.

Old Browsers (IE5 and IE6)

• Old versions of Internet Explorer (5/6) use an ActiveX object instead of the
XMLHttpRequest object: variable = new ActiveXObject("Microsoft.XMLHTTP");

• To handle IE5 and IE6, check if the browser supports the XMLHttpRequest object,
or else create an ActiveX object:
AJAX
AJAX - The XMLHttpRequest Object

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, Specifies the request
user, psw)
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
AJAX
AJAX - The XMLHttpRequest Object

XMLHttpRequest Object Properties


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
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")
AJAX
The XMLHttpRequest object is used to exchange data with a server.

Send a Request To a Server

• To send a request to a server, we use the open() and send() methods of the
XMLHttpRequest object:

Method Description
open(method, url, Specifies the type of request
async)
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
AJAX
The XMLHttpRequest object is used to exchange data with a server.

• Send a Request To a Server using GET Requests - A simple GET request:


<!DOCTYPE html>
<html>
<body><h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p> The XMLHttpRequest Object
<script>
function loadDoc() { This content was requested using the GET
var xhttp = new XMLHttpRequest(); method.
Requested at: 4/29/2021 3:28:04 AM
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText; } };
xhttp.open("GET", "demo_get.asp", true);
xhttp.send(); }
</script> </body> </html>
AJAX
The XMLHttpRequest object is used to exchange data with a server.

• Send a Request To a Server using POST Requests

<!DOCTYPE html>
<html>
<body><h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p> The XMLHttpRequest Object
<script>
This content was requested using the GET
function loadDoc() { method.
var xhttp = new XMLHttpRequest(); Requested at: 4/29/2021 3:28:04 AM
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText; } };
xhttp.open(“POST", "demo_get.asp", true);
xhttp.send(); }
</script> </body> </html>
AJAX
The url - A File On a Server

• The url parameter of the open() method, is an address to a file on a server:

xhttp.open("GET", "ajax_test.asp", true);

• The file can be any kind of file, like .txt and .xml, or server scripting files like .asp
and .php (which can perform actions on the server before sending the response
back).

Asynchronous - True or False?


• Server requests should be sent asynchronously.
• The async parameter of the open() method should be set to true:
xhttp.open("GET", "ajax_test.asp", true);
• By sending asynchronously, the JavaScript does not have to wait for the server
response, but can instead:
 execute other scripts while waiting for server response
 deal with the response after the response is ready
AJAX
The onreadystatechange Property

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

• The function is defined in the onreadystatechange property of the


XMLHttpRequest object: - Example

Synchronous Request

• To execute a synchronous request, change the third parameter in the open()


method to false: xhttp.open("GET", "ajax_info.txt", false);

• Sometimes async = false are used for quick testing. You will also find synchronous
requests in older JavaScript code.

• Since the code will wait for server completion, there is no need for an
onreadystatechange function - Example
AJAX
Synchronous Request

• Synchronous XMLHttpRequest (async = false) is not recommended because the


JavaScript will stop executing until the server response is ready. If the server is
busy or slow, the application will hang or stop.

• Synchronous XMLHttpRequest is in the process of being removed from the web


standard, but this process can take many years.

• Modern developer tools are encouraged to warn about using synchronous


requests and may throw an InvalidAccessError exception when it occurs.
AJAX
AJAX - Server Response

• The onreadystatechange Property

• The readyState property holds the status of the XMLHttpRequest.

• The onreadystatechange property defines a function to be executed when the


readyState changes.

• The status property and the statusText property holds the status of the
XMLHttpRequest object.
AJAX
AJAX - Server Response
Property Description
The onreadystatechange
•onreadystatec Defines a Property
function to be called when the readyState property
hange changes
• The readyState property holds the status of the XMLHttpRequest.
readyState Holds the status of the XMLHttpRequest.
• The onreadystatechange property
0: request not defines a function to be executed when the
initialized
readyState changes.
1: server connection established
2: request received
• The status property and the
3: processing statusText property holds the status of the
request
XMLHttpRequest4: request
object. 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")


AJAX
AJAX - Server Response

• The onreadystatechange function is called every time the readyState changes.

• When readyState is 4 and status is 200, the response is ready - Example

• The onreadystatechange event is triggered four times (1-4), one time for each
change in the readyState.

You might also like