Week12 Theory
Week12 Theory
1. Introduction to AJAX
2. AJAX Request and Response
3. Access JSON using AJAX
4. Introduction to jQuery
5. jQuery Selectors
6. jQuery Events
Introduction to AJAX
What is AJAX
1. An event occurs in a web page when 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
Example
• 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 loadDoc().
• The function requests data from a web server and displays it.
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 XMLHttpRequest Object
• The keystone of AJAX is the XMLHttpRequest object.
• The XMLHttpRequest object can be used to exchange data
with a web server behind the scenes.
• it is possible to update parts of a web page, without
reloading the whole page.
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
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 Request
• To send a request to a server, 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)
To get some specific data using GET method, need to use below example
Example 1:
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
Example 2:
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
POST Requests
simple POST request
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
By sending asynchronously, the JavaScript does not have to wait for the
server response.
• execute other scripts while waiting for server response
• deal with the response after the response is ready
Synchronous Requests
A synchronous request blocks the client until operation completes i.e.
browser is unresponsive.
To execute a synchronous request, change the third parameter in the
open() method to false:
xhttp.open("GET", "ajax_info.txt", false);
Method Description
getResponseHeader() Returns specific header information from the server resource
getAllResponseHeaders Returns all the header information from the server resource
()
Sending Data
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
Receiving Data
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Example of JSON
myTutorials.txt
[
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]
Introduction to jQuery
What is jQuery?
There are lots of other JavaScript libraries out there but jQuery is probably the
most popular, and also the most extendable.
Many of the biggest companies on the Web use jQuery, such as:
• Google
• Microsoft
• IBM
• Netflix
Example
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
When a user clicks on a button, all <p> elements will be hidden:
The #id Selector
• jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.
• An id should be unique within a page, so you should use the #id
selector when you want to find a single, unique element.
• To find an element with a specific id, write a hash character,
followed by the id of the HTML element $("#test")
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
Example
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
Examples:
• moving a mouse over an element
• selecting a radio button
• clicking on an element
dblclick()
• The dblclick() method attaches an event handler function to an HTML element.
• The function is executed when the user double-clicks on the HTML element
$(document).ready(function(){
$("p").dblclick(function(){
$(this).hide();
});
});
mouseenter()
• The mouseenter() method attaches an event handler function to an HTML
element.
• The function is executed when the mouse pointer enters the HTML element
$(document).ready(function(){
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
});
mouseleave()
• The mouseleave() method attaches an event handler function to an HTML
element.
• The function is executed when the mouse pointer leaves the HTML element
$(document).ready(function(){
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
});
Output
References
• MySQL - www.mysql.com
• W3Schools Online Web Tutorials- www.w3schools.com
• PHP Manual - www.php.net
• Free Online Tutorials - www.javatpoint.com
Books
• Sams Teach Yourself Ajax JavaScript and PHP All in One; Phil
Ballard and Michael Moncur;
• Sams Publishing; 2010
• JavaScript Phrasebook; Christian Wenz; Sams Publishing; 2007
• PHP and MySQL Web Development, 4/E; Luke Welling and Laura
Thomson; AddisonWesley Professional; 2009
• JavaScript for Programmers Paul J. Deitel and Harvey M. Deitel;
Prentice Hall; 2009