Ajax Studio CAD
Ajax Studio CAD
Ajax Studio CAD
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.
$.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
beforeSend:function()
You can define an action before sending your ajax request
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
$.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
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.
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.
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(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.
===================================================================================
===========================================
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:
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.
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));
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
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.
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();
Some API’s will also allow you attach your client ID to the url of the request like
so.
readyState stores a number ranging from 0–4 showing the progress 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>
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.
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.
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 Example
Let AJAX change this text
Change Content
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 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 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.
===================================================================================
====================================
https://www.w3schools.com/xml/ajax_xmlhttprequest_create.asp
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.
Example
var xhttp = new XMLHttpRequest();
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.
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");
}
===================================================================================
================
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
-----------------------------------------------------------------------------------
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.
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 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).
By sending asynchronously, the JavaScript does not have to wait for the server
response, but can instead:
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:
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;
- 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
-----------------------------------------------------------------------------------
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")
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.
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
}
-----------------------------------------------------------------------------------
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
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
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();
}
};
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
Example
Get CD info
Example Explained
When a user clicks on the "Get CD info" button above, the loadDoc() function is
executed.
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;
}
===================================================================================
===
https://www.w3schools.com/xml/ajax_php.asp
Example
Start typing a name in the input field below:
Example Explained
------------------
- In the example above, when a user types a character in the input field, a
function
called "showHint()" is executed.
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.
<?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";
$hint = "";
Example
Start typing a name in the input field below:
Example Explained
In the example above, when a user types a character in the input field, a function
called "showHint()" is executed.
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.
<%
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"))
===================================================================================
======
https://www.w3schools.com/xml/ajax_database.asp
Example
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 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');
}
$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.
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.
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.
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