Ajax Studio CAD

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

// https://stackoverflow.

com/questions/22963610/ajax-explained-in-detail

$.ajax( {
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function() {
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"> <img
src="/images/loading.gif" alt="Loading..." /> </div>');
},
success:function(data) {
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i) {
$('#ajax-panel').append('<h4>' + $(this).find('title').text() +
'</h4> <p>' + $(this).find('link').text() + '</p>');
} );
},
error:function() {
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"> <strong> Oops! </strong> Try
that again in a few moments. </p>');
}
} );

Ajax is asynchronous, which mean you can use it to get new informations from the
server without reloading the whole page.

Here's an explanation of your code :

$.ajax({
$ is the JQuery object, on which you're calling the ajax function

type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them
in php with $_POST['variable_name'].
You could also put GET instead

url: 'http://kyleschaeffer.com/feed/',
the url you want to reach

data: { postVar1: 'theValue1', postVar2: 'theValue2' },


as you're sending your request with POST, you cannot pass data directly from
the URL. So you have to pass them like that.
{ nameVar: 'value', .... } If you were sending with GET, you could directly
write them into url like :
"http://my_url.php?var1=val1&var2=val2 etc ...

beforeSend:function()
You can define an action before sending your ajax request

$('#ajax-panel').html('<div class="loading"> <img src="/images/loading.gif"


alt="Loading..." /> </div>');
Here, inside your div "ajax-panel" you want to write some content. (a div
"loading" and a picture inside "loading").

success:function(data)
If your request is successful, you can do something. By successful it means
if server answer 200 i guess,
anyway ... If you have a response from server... ;)

$('#ajax-panel').empty();
You delete content into ajax-panel

$(data).find('item').each(function(i) {
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' +
$(this).find('link').text() + '</p>');
} );
You're adding some html AFTER (append) the ajax-panel div

error:function()
Not sure you were looking for that, hope that help you ;)

AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology
help us to load data from the server
without a browser page refresh.

If you are new with AJAX, I would recommend you go through our Ajax Tutorial before
proceeding further.

JQuery is a great tool which provides a rich set of AJAX methods to develope next
generation web application

Take a took at this

$.ajax( {
type : varType, // GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, // Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, // Expected data format from server
processdata : varProcessData, // True or False
success : function(msg) {
// On Successfull service call
},
error : function() {
// When Service call fails
}
} );

===================================================================================
==========================
https://www.keycdn.com/support/ajax-programming

What Is Ajax Programming - Explained


------------------------------------
Updated on October 4, 2018

Ajax is short for Asynchronous JavaScript and XML, which refers to a set of web
development techniques rather than an
actual programming language. Ajax however, is widely used in client-side
programming (e.g. JavaScript) to allow for data
to be sent and received to and from a database / server. What’s special about using
Ajax programming is that you can
exchange data in the background without actually disturbing the user experience. As
Wikipedia puts it,

By decoupling the data interchange layer from the presentation layer, Ajax allows
for web pages, and by extension web
applications, to change content dynamically without the need to reload the entire
page.

This method is extremely useful both for website performance and usability. Since
asynchronous loading is non-render
blocking, it will allow your page’s HTML to continue parsing even if it encounters
a script tag. From a usability standpoint,
visitors can benefit from seeing certain information generated without having to
reload the page. This is a huge step
forward for improving perceived performance.

How Ajax Works#


---------------
The way Ajax works is quite simple. To help explain, check out the image below
which shows a comparison between the
conventional method of requesting data from a web server vs using the Ajax method.
I’ll explain what is taking place
on either side in the section below.

Conventional Method#
--------------------
Starting from the top of the conventional method, we can see that the browser wants
to make a request to the web server
for some data. therefore the following takes place.

An HTTP request is made from the browser to the web server. Therefore, the user
must wait for this request to be processed
and return a response before they can see the data requested.
The request reaches the web server and retrieves the appropriate data.
The requested data is then sent back to the browser and the user is able to see
that data.

Ajax Method#
------------
The following takes place when requesting the same data, however, this time using
the Ajax method.

1. The browser performs a JavaScript call to the Ajax engine. In other words,
create an XMLHttpRequest object.
2. In the background, an HTTP request is made to the server and the
appropriate data is retrieved.
3. HTML, XML, or JavaScript data is returned to the Ajax engine which then
delivers the requested data to the browser.

Using this method, the user does not experience any downtime from the point when
they made a request to the point when they
receive the actual information.

Asynchronous vs Synchronous Loading#


------------------------------------
When it comes to loading scripts, traditionally scripts were loading using the
synchronous method. This was more or less
of a “first-come first-served” process whereas if during the page rendering
process, the HTML came across a script tag then
it would load that script tag in sequence, thus blocking the parsing of HTML. Once
the script was fully loaded, the HTML would
continue to parse and load the rest of the web page.

As we can see by the image below, there are 3 synchronous scripts being loaded one
after another. **However, there is also
an asynchronous script which can be loaded at the same time as the synchronous
script which makes for a much more efficient
loading process

Ajax Programming Example#


-------------------------
As far as loading a script asynchronously goes, this is very easy. To do so, you
simply need to add the async attribute to
your script tag. For example, if we are loading a script located at js/example.js
then we could define the following.

<script src="example.js" async> </script>


As for using Ajax functions, there are a ton of possibilities. First off, a
typical Ajax function will have the two
following components.

$.ajax(url [, settings])
The Ajax url parameter defines the URL for which you want to make a request
to and the settings parameter is used to
configure the actual Ajax request. Check out the full list of settings
options available on the official jQuery and
Ajax documentation page.

$.ajax('demo.html', {
success: function(result) {
$('#testdiv').html(result);
}
} );
The example above is a simple demonstration of how jQuery and Ajax can be
used. The URL for which we make a request to
is demo.html. We then take the result and insert it into the element that
contains the ID #testdiv.

There are many other more complex and in-depth examples out there for using jQuery
and Ajax, for more examples check out
Sitepoint’s How to Use jQuery's $.ajax() Function post.

Ajax Programming - In Summary#


------------------------------
As previously mentioned, using Ajax programming methods is not a programming
language in and of itself. Rather, it combines
multiple technologies in a manner that renders the access of data more efficiently
and effectively. Wherever possible,
ensure that you are loading your scripts using async and implementing Ajax
functions wherever it makes sense so that users
can access the information they need much faster.

===================================================================================
===========================================
https://en.wikipedia.org/wiki/Ajax_(programming)

...............

Technologies
------------
The conventional model for a Web Application versus an application using Ajax
The term Ajax has come to represent a broad group of Web technologies that can be
used to implement a Web application that
communicates with a server in the background, without interfering with the current
state of the page. In the article that
coined the term Ajax,[1][3] Jesse James Garrett explained that the following
technologies are incorporated:

- HTML (or XHTML) and CSS for presentation


- The Document Object Model (DOM) for dynamic display of and interaction with data
JSON or XML for the interchange of data, and XSLT for its manipulation
- The XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together

Since then, however, there have been a number of developments in the technologies
used in an Ajax application, and in the
definition of the term Ajax itself. XML is no longer required for data interchange
and, therefore, XSLT is no longer required
for the manipulation of data. JavaScript Object Notation (JSON) is often used as an
alternative format for data interchange,[13]
although other formats such as preformatted HTML or plain text can also be used.
[14] A variety of popular JavaScript libraries,
including JQuery, include abstractions to assist in executing Ajax requests.

..............

Examples
--------
JavaScript example
An example of a simple Ajax request using the GET method, written in JavaScript.

get-ajax-data.js:
-----------------
// This is the client-side script.
// Initialize the HTTP request.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'send-ajax-data.php');
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.responseText); // 'This is the
output.'
} else {
console.log('Error: ' + xhr.status); // An error
occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);

send-ajax-data.php:
-------------------
<?php
// This is the server-side script.

// Set the content type.


header('Content-Type: text/plain');

// Send the data back.


echo "This is the output.";
?>

Many developers dislike the syntax used in the XMLHttpRequest object, so some of
the following workarounds have
been created.

jQuery example
--------------
The popular JavaScript library jQuery has implemented abstractions which enable
developers to use Ajax more conveniently.
Although it still uses XMLHttpRequest behind the scenes, the following is a client-
side implementation of the same example
as above using the 'ajax' method.

$.ajax( {
type: 'GET',
url: 'send-ajax-data.php',
dataType: "JSON", // data type expected from server
success: function (data) {
console.log(data);
},
error: function(error) {
console.log('Error: ' + error);
}
} );

jQuery also implements a 'get' method which allows the same code to be written more
concisely.

$.get('send-ajax-data.php').done(function(data) {
console.log(data);
} ).fail(function(data) {
console.log('Error: ' + data);
} );

Fetch example
-------------
Fetch is a new native JavaScript API.[27] According to Google Developers
Documentation, "Fetch makes it easier to make
web requests and handle responses than with the older XMLHttpRequest."

fetch('send-ajax-data.php')
.then(data => console.log(data))
.catch (error => console.log('Error:' + error));

ES7 async/await example:


------------------------

async function doAjax() {


try {
const res = await fetch('send-ajax-data.php');
const data = await res.text();
console.log(data);
} catch (error) {
console.log('Error:' + error);
}
}
doAjax();

As seen above, fetch relies on JavaScript promises.

See also
- ActionScript:
https://en.wikipedia.org/wiki/ActionScript
- Comet (programming) (also known as Reverse Ajax)
https://en.wikipedia.org/wiki/Comet_(programming)
- Google Instant
https://en.wikipedia.org/wiki/Google_Instant
- HTTP/2
https://en.wikipedia.org/wiki/HTTP/2
- List of Ajax frameworks
https://en.wikipedia.org/wiki/List_of_Ajax_frameworks
- Node.js
https://en.wikipedia.org/wiki/Node.js
- Remote scripting
https://en.wikipedia.org/wiki/Remote_scripting
- Rich Internet application
https://en.wikipedia.org/wiki/Rich_Internet_application
- WebSocket
https://en.wikipedia.org/wiki/WebSocket
- HTML5
https://en.wikipedia.org/wiki/HTML5
- Javascript
https://en.wikipedia.org/wiki/JavaScript
===================================================================================
=============================================
https://codeburst.io/a-gentle-introduction-to-ajax-1e88e3db4e79

A gentle Introduction to Ajax.


------------------------------

Imagine you’re deep into your Facebook feeds, you like a post, the page reloads and
you had to start all over again.

Not quite painful right, think of how many times you must have reloaded when you
like up to 5 posts.

This was the state of the web before the year 2000 when Microsoft introduced the
Ajax technology (XMLHttpRequest object)
to Internet Explorer which facilitated communication to servers without reloading
the page. Soon after other big companies
like Google, and Facebook started incorporating it.

Ajax, as you might already know, stands for Asynchronous JavaScript and XML. The
word Asynchronous is used to mean pack of
events happening at an irregular intervals. You might be thinking what’s with the
XML, XML is a format for passing data from
server to client, it was dropped in favor of HTML and JSON. Yea, these days, you
can pass raw HTML and JSON around the web
using Ajax. JSON is a more lighter and straight forward format for passing data
around the web.

Basic Ajax request.


-------------------
To write a basic Ajax request, we need to…

1, Make an instance of the XMLHttpRequest object.


2, Open the request.
3, Send the request.
4, Handle the request.

var request = new XMLHttpRequest();


request.onreadystate = handleResponse;
request.open('GET', 'url', true);
request.send();
function handleRequest() {
console.log(request.responseText);
}

To explain the code above.


-------------------------
- The first line makes an instance of the XMLHttpRequest object.
- The second line contains an event (onreadystate), this event fires when the state
of the request changes. And the event
handler (handleResponse) handles the event and logs the response from the
server to the browser console.
More on the request state later on.
- The third line opens the request. The open() method takes three arguments.
- The first is the action of the request. It could be:
GET (to retrieve data),
POST (to insert data),
UPDATE (to update data) and
DELETE (to delete data).
- The second is the URL to fetch the data from. The third is a boolean value
that determines if the request is
Asynchronous or not.
A True value means an Asynchronous request and
False, synchronous (the page will reload), we don’t want that
right?.

This is all we need to make an Ajax request. Quite simple right? Now, let’s make a
real life example.

Unsplash API
------------
To cement our basic knowledge, we’re going to have an example.
We’ll try to get data Asynchronously from the unsplash.com API, the program will
search the API and return images that
match our keyword.
Unsplash is a photo collection site. It consists of high quality photos.
So for you to partake, you’ll need to register with Unsplash as a developer,
they’ll give you a key so you can have
access to the API.
Head to Unsplash now, register as a developer and create a new application. Now you
have to understand that unsplash
has to take note of the number of API calls you make and take care of security. So
you’ll either attach your key to the
request url or make a request header. Don’t worry if you don’t understand, an
example here…

function handleRequest() {
if(this.readyState == 4 && this.status == 200) {
// Explain this in a bit.
console.log(JSON.parse(request.responseText));
}
}

var url;
url = "https://api.unsplash.com/search/photos/?query=home"; //We are
searching for the query home.
var request = new XMLHttpRequest();
request.onreadystatechange = handleRequest;
request.open('GET',url,true);
request.setRequestHeader('Authorization','Client-ID your-client-id'); //
Unique client ID. (line 12)
request.send();

Let’s break down the code above.


The novel in this case is line 12 right?.
Line 12 sets a request header. Basically, you would want to put your id as a value
of the Authorization property.
This verifies you were permitted to utilize their API. Without this, most API’s
will surely end a 401 error.
In case you get that later, just check your client ID is proper.

Some API’s will also allow you attach your client ID to the url of the request like
so.

var url = "https://api.unsplash.com/search/photos/?query=home&client-id=your-


client-id";

You wouldn’t need a setRequestHeader() method anymore.


You might have also noticed that we have modified the handleRequest function. We
introduced two new properties of the
XMLHttpRequest object. readyState and status.

readyState stores a number ranging from 0–4 showing the progress of the request.

0 - means request has not been initialized.


1 - means the server connection was established.
2 - means request was sent.
3 - means request is processed.
4 - request was successful and response if ready.

Status property also shows the success of the request.

200 - success.
404 - page not found.
403 - forbidden request.

So, see why we used 4 and 200, to make sure the response was ready before using
them.

Copy the above code to your browser console with your unique API ID, hit enter and
see what is logged out to the console.
Something complex right?.

If you look closely, you’ll not notice it’s a large object comprising of about 2600
objects. Ok, you can’t see that even if you look closely.
Let’s take this further, search in the image above for the urls key, it has full,
raw, regular, small and thumb values. We could modify the code above to add the
image to the web page asynchronously by pointing our src attribute to the url of
the image.

<!DOCTYPE html>

<html>

<head>
<title> Async request </title>
</head>

<body>
<p> click on the button to add an image to the page </p>
<button type="button"> Get image </button>
<img src="" width="100%">
</body>

<script>
//ES5 for simplicity.
function sendRequest() {
var url;
url = "https://api.unsplash.com/search/photos/?query=home";
var request = new XMLHttpRequest();
request.onreadystatechange = handleRequest; // callback to
insert the image into the page...
request.open('GET',url,true);
request.setRequestHeader('Authorization','Client-ID your-unique-id');
request.send();

function handleRequest() {
if(this.readyState === 4 && this.status === 200) {
var response = JSON.parse(request.responseText);
var img = document.querySelector('img');
img.src = response.results[0].urls.full;
}
}
}
var btn = document.querySelector('button');
btn.addEventListener('click',sendRequest); //callback to handle the
click event...
</script>

</html>

Here’s how this works in a browser.

Sending data to a server


So far, we’ve been dealing with requesting data from a server. What if we needed to
save data Asynchronously.
Think about form details and other user information. That’s quite simple and not
different from the already known format
except that we’ll use a POST method this time.

var data = 'name=victor&age=19';


function handleRequest() {
if (this.readyState === 4 && this.status === 200) {
alert('data was saved');
}
}
var request = new XMLHttpRequest();
request.onreadystatechange = handleRequest;
request.open('POST',server-url,true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data);

In this example, we have some form parameters (data) we would like to send to a
server without reloading the page.
the data is sent to the server and the message is alerted only when the data was
successfully saved.

What then happens when there’s a problem in the server connection?. Well, we’ll
treat that in the next phase.

Event and Error handling.


------------------------
So far, we’ve only talked about instances where the request is successful. A lot of
things can go wrong while making
async requests. Take this example.
var request = new XMLHttpRequest();
request.addEventListener('progress',checkProgress); //fires when the
readyState changes.
request.addEventListener('abort',abortMessage); // fires when the
request is aborted.
request.addEventListener('error',errorMessage); // fires when an error
occurs
request.addEventListener('load',handleRequest); // fires only when the
request is successfull and data is sent back to the browser.

function handleRequest() {
console.log(request.responseText);
}
function checkProgress(progress) {
var percentage = (progress.loaded / progress.total) * 100;
console.log(percentage);
}
function errorMessage() {
console.log('sorry there was an error, please try again');
}
function abortMessage() {
console.log('sorry, this request was aborted');
}
request.open('GET',url,true);
request.send();

As you can see in the above code, we use the addEventListener method to attach
appropriate event listeners
to different events that occur when async request is done.

On line 11, we see something new however. The progress.loaded and progress.total.
The loaded property holds the current
state of the request and total holds the total request state (4). So dividing
progress.loaded by progress.total will result
in a number less than one when the request is not complete or one when the request
is complete and the response returns.

Example.
--------
(3/4) * 100 = 75%. *almost complete*.
(4/4) * 100 = 100%. *complete*.

Using this method, we could give good user experience, offering users retry again
messages when requests fail.

Wow!!!.

That’s all for now. This post is aimed at giving an under-the-hood beginner
explanation of the XMLHttpRequest object,
here’s a post that explains Ajax with jQuery; an easier way to write Asynchronous
requests.

Easier Asynchronous requests with jQuery.


-----------------------------------------
Imagine the amount of the web that consists of repeated code. It’s not too much of
a bad idea to let computers do the…
medium.com

I’ll appreciate a clap or two so your friends could see this too. I guess they’ll
be cool with it too.

===================================================================================
=======================================
https://www.w3schools.com/xml/ajax_intro.asp

AJAX Introduction
-----------------

AJAX is a developer's dream, because you can:

Update a web page without reloading the page


Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background

Try it Yourself Examples in Every Chapter


In every chapter, you can edit the examples online, and click on a button to view
the result.

AJAX Example
Let AJAX change this text
Change Content

AJAX Example Explained

HTML Page
---------
<!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>

The HTML page contains a <div> section and a <button>.

The <div> section is used to display information from a server.

The <button> calls a function (if it is clicked).

The function requests data from a web server and displays it:

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

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


---------------
AJAX

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

===================================================================================
====================================
https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp

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 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, IE7+, Edge, Safari Opera) have a built-in
XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:


variable = new XMLHttpRequest();

Example
var xhttp = new XMLHttpRequest();

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.

Old Versions of Internet Explorer (IE5 and IE6)


-----------------------------------------------
Old versions of Internet Explorer (IE5 and IE6) 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:

Example
-------
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

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
------------------------------ -----------------------------------------
------
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")

===================================================================================
================
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

AJAX - Send a Request To a Server


---------------------------------
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:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

-----------------------------------------------------------------------------------
Method Description
------------------------------ -----------------------------------------
------
open(method, url, async) Specifies the type of request
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)

GET or POST?
------------
GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

- A cached file is not an option (update a file or database on the server).


- Sending a large amount of data to the server (POST has no size limitations).
- Sending user input (which can contain unknown characters), POST is more robust
and secure than GET.

GET Requests
------------
A simple GET request:

Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

In the example above, you may get a cached result. To avoid this, add a unique ID
to the URL:

Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();

If you want to send information with the GET method, add the information to the
URL:

Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();

POST Requests
-------------
A simple POST request:

Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:

Example

-----------------------------------------------------------------------------------
Method Description
------------------------------ -----------------------------------------
------
setRequestHeader(header, value) Adds HTTP headers to the request
header: specifies
the header name
value:
specifies the header value

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

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 XMLHttpResponse


object:

Example
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();
You will learn more about onreadystatechange in a later chapter.

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
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

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

===================================================================================
==============
https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp

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.

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

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

Using a Callback Function


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

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) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}

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

Server Response Properties


--------------------------

-----------------------------------------------------------------------------------
Property Description
------------------------------ -----------------------------------------
------
responseText get the response data as a string
responseXML get the response data as XML data
Server Response Methods

-----------------------------------------------------------------------------------
Method Description
------------------------------ -----------------------------------------
------
getResponseHeader() Returns specific header information
from the server resource
getAllResponseHeaders() Returns all the header information from
the server resource

The responseText Property


-------------------------
The responseText property returns the server response as a JavaScript string, and
you can use it accordingly:

Example
document.getElementById("demo").innerHTML = xhttp.responseText;

The responseXML Property


------------------------
The XML HttpRequest object has an in-built XML parser.
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:

Example
Request the file cd_catalog.xml and parse the response:

xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();

You will learn a lot more about XML DOM in the DOM chapters of this tutorial.
The getAllResponseHeaders() Method
----------------------------------
The getAllResponseHeaders() method returns all header information from the server
response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};

The getResponseHeader() Method


------------------------------
The getResponseHeader() method returns specific header information from the server
response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

===================================================================================
=========
https://www.w3schools.com/xml/ajax_xmlfile.asp

AJAX XML Example


----------------
AJAX can be used for interactive communication with an XML file.

AJAX XML Example


---------------
The following example will demonstrate how a web page can fetch information from an
XML file with AJAX:

Example
Get CD info

Example Explained
When a user clicks on the "Get CD info" button above, the loadDoc() function is
executed.

The loadDoc() function creates an XMLHttpRequest object, adds the function to be


executed when the
server response is ready, and sends the request off to the server.

When the server response is ready, an HTML table is built, nodes (elements) are
extracted from the
XML file, and it finally updates the element "demo" with the HTML table filled with
XML data:

LoadXMLDoc()
------------
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr> <th>Title</th> <th>Artist</th> </tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr> <td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td> <td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td> </tr>";
}
document.getElementById("demo").innerHTML = table;
}

The XML File


-------------
The XML file used in the example above looks like this: "cd_catalog.xml".

===================================================================================
===
https://www.w3schools.com/xml/ajax_php.asp

AJAX PHP Example


----------------
AJAX is used to create more interactive applications.

AJAX PHP Example


----------------
The following example demonstrates how a web page can communicate with a web server
while a user types
characters in an input field:

Example
Start typing a name in the input field below:

First name: _____________ Suggestions: _____________

Example Explained
------------------
- In the example above, when a user types a character in the input field, a
function
called "showHint()" is executed.

- The function is triggered by the onkeyup event.

- Here is the HTML code:

Example
<html>

<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{

document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>

<body>
<p> <b> Start typing a name in the input field below: </b> </p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p> Suggestions: <span id="txtHint"> </span> </p>
</body>

</html>

Code explanation:
-----------------
First, check if the input field is empty (str.length == 0). If it is, clear the
content of the
txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:


- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a PHP file (gethint.php) on the server
- Notice that q parameter is added gethint.php?q="+str
- The str variable holds the content of the input field

The PHP File - "gethint.php"


----------------------------
The PHP file checks an array of names, and returns the corresponding name(s) to the
browser:

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;
?>
===================================================================================
========
https://www.w3schools.com/xml/ajax_asp.asp

AJAX ASP Example


----------------
AJAX is used to create more interactive applications.

AJAX ASP Example


-----------------
The following example will demonstrate how a web page can communicate with a web
server while a
user type characters in an input field:

Example
Start typing a name in the input field below:

First name: _____________ Suggestions: _________________

Example Explained
In the example above, when a user types a character in the input field, a function
called "showHint()" is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example
<html>

<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{

document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.asp?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>

<body>
<p> <b> Start typing a name in the input field below: </b> </p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p> Suggestions: <span id="txtHint"> </span> </p>
</body>

</html>

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the
content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

- Create an XMLHttpRequest object


- Create the function to be executed when the server response is ready
- Send the request off to an ASP file (gethint.asp) on the server
- Notice that q parameter is added gethint.asp?q="+str
- The str variable holds the content of the input field

The ASP File - "gethint.asp"


---------------------------
The ASP file checks an array of names, and returns the corresponding name(s) to the
browser:

<%
response.expires = -1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
a(3)="Cinderella"
a(4)="Diana"
a(5)="Eva"
a(6)="Fiona"
a(7)="Gunda"
a(8)="Hege"
a(9)="Inga"
a(10)="Johanna"
a(11)="Kitty"
a(12)="Linda"
a(13)="Nina"
a(14)="Ophelia"
a(15)="Petunia"
a(16)="Amanda"
a(17)="Raquel"
a(18)="Cindy"
a(19)="Doris"
a(20)="Eve"
a(21)="Evita"
a(22)="Sunniva"
a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky"
'get the q parameter from URL
q=ucase(request.querystring("q"))

'lookup all hints from array if length of q>0


if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
end if

'Output "no suggestion" if no hint were found


'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>

===================================================================================
======
https://www.w3schools.com/xml/ajax_database.asp

AJAX Database Example


---------------------
AJAX can be used for interactive communication with a database.

AJAX Database Example


---------------------
The following example will demonstrate how a web page can fetch information from a
database with AJAX:

Example

Customer info will be listed here...

Example Explained - The showCustomer() Function


-----------------------------------------------
When a user selects a customer in the dropdown list above, a function called
"showCustomer()" is executed. The function is triggered by the "onchange" event:

showCustomer
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}

The showCustomer() function does the following:

- Check if a customer is selected


- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (q) is added to the URL (with the content of the dropdown
list)

The AJAX Server Page


--------------------
The page on the server called by the JavaScript above is an PHP file called
"getcustomer.php".

The source code in "getcustomer.php" runs a query against a database, and returns
the result in an HTML table:

<?php
$mysqli = new mysqli("servername", "username", "password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}

$sql = "SELECT customerid, companyname, contactname, address, city, postalcode,


country
FROM customers WHERE customerid = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();

echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>

https://www.w3schools.com/xml/ajax_applications.asp

XML Applications
This chapter demonstrates some HTML applications using XML, HTTP, DOM, and
JavaScript.

The XML Document Used


In this chapter we will use the XML file called "cd_catalog.xml".

Display XML Data in an HTML Table


This example loops through each <CD> element, and displays the values of the
<ARTIST> and the <TITLE> elements in an HTML table:

Example
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse:collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>

<table id="demo"></table>

<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>

</body>
</html>
For more information about using JavaScript and the XML DOM, go to DOM Intro.

Display the First CD in an HTML div Element


This example uses a function to display the first CD element in an HTML element
with id="showCD":

Example
displayCD(0);

function displayCD(i) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this, i);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}

function myFunction(xml, i) {
var xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("CD");
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
Navigate Between the CDs
To navigate between the CDs, in the example above, add a next() and previous()
function:

Example
function next() {
// display the next CD, unless you are on the last CD
if (i < x.length-1) {
i++;
displayCD(i);
}
}

function previous() {
// display the previous CD, unless you are on the first CD
if (i > 0) {
i--;
displayCD(i);
}
}
Show Album Information When Clicking On a CD
The last example shows how you can display album information when the user clicks
on a CD:

Example
function displayCD(i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

https://www.w3schools.com/xml/ajax_examples.asp

AJAX Examples
Try it Yourself - Examples
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

You might also like