SYST 28043
Web Technologies
SYST 28043
Web Technologies
AJAX
Javascript ReviewJavascript Review
Quick review of some Javascript:document.getElementById(string)Retrieves an object corresponding to the element in your html file with the name [string]
var divObject = document.getElementById(‘display’);
04/21/23 Wendi Jollymore, ACES 2
Javascript ReviewJavascript Review
Quick review of some Javascript:object.innerHTML propertyReferences the contents of the tag
var divObject = document.getElementById(‘display’);
divObject.innerHTML = “This is some text.”;
04/21/23 Wendi Jollymore, ACES 3
Javascript ReviewJavascript Review
Quick review of some Javascript:Accessing other properties using dot notation:
var divObject = document.getElementById(‘txtTitle’);
if (txtTitle.value == “”) {
alert(“Title can’t be empty.”);
}
Accessing style properties:divObject.style.fontSize = “1.5em”;
http://www.w3schools.com/htmldom/default.asphttp://www.w3schools.com/htmldom/default.asp
04/21/23 Wendi Jollymore, ACES 4
04/21/23 Wendi Jollymore, ACES 5
What is AJAX?What is AJAX?
AJAX:Asynchronous Javascript And XMLMakes a web page act more like an application
Normally processing occurs when the web page causes browser to make requests from web server via httpWeb server sends responses back to browserUser waits while request is sent, response received, and page reloads with response data
AJAX can work behind the scenes to pages don’t REFRESH
04/21/23 Wendi Jollymore, ACES 6
What is AJAX?What is AJAX?
AJAX technology has actually been around for a long time (1998)Didn’t catch on until 2005:
Google Maps, Google Suggesthttp://www.adaptivepath.com/ideas/essays/archives/000385.php
04/21/23 Wendi Jollymore, ACES 7
AJAX ExampleAJAX Example
Check out these demos:http://demos.openrico.org/inner_ajax_HTMLhttp://demos.openrico.org/complex_ajax
04/21/23 Wendi Jollymore, ACES 8
How AJAX WorksHow AJAX Works
AJAX uses asynchronous communicationCan communicate with server multiple times while other things are going onSome call this “threading” but some say it’s not the same thing
AJAX accomplishes this using a few elements:
Presentation (XHTML, CSS)Data (XML format, Database, etc)Code (Javascipt)The XMLHttpRequest object
04/21/23 Wendi Jollymore, ACES 9
How AJAX WorksHow AJAX Works
Using Javascript and the XMLHttpRequest object:
Javascript can request data from the server behind the scenesThe results from requests can be displayed in the page without refreshing (e.g. using the innerHTML attribute)
PHP – How does this fit in?Data is stored on the serverSome code might be needed on the server to process the data before it’s passed to the Javascript codeE.g. executing a query that selects records from a database
04/21/23 Wendi Jollymore, ACES 10
Making an AJAX ExampleMaking an AJAX Example
Create a folder for this exampleCreate a plain-text file called example.dat
Put any text in it – a sentence, some words, whatever
Create an XHTML pageAdd a form (don’t worry about method/action)Add a button (NOT a Submit button!)Add a <div><div> with an id value!
04/21/23 Wendi Jollymore, ACES 11
Making an AJAX ExampleMaking an AJAX Example
Create a new Javascript (.js) file:var xmlHttp= false;
Creates a variable called xmlHttp and initializes it to false
If we successfully create an XMLHttpRequest object, this variable will hold itIf not, it will stay falseJavascript thinks anything that isn’t false, is true!
04/21/23 Wendi Jollymore, ACES 12
Making an AJAX ExampleMaking an AJAX Example
if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest();} else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
The XMLHttpRequest ObjectThe XMLHttpRequest Object
This object is what handles the requests and responses behind the scenesonreadystatechange property
Contains the function that will process the server’s response to a request
E.g. display the response in a <div>Most programmers use anonymous functions (yuck!)
The function will execute each time the state of the response changes
04/21/23 Wendi Jollymore, ACES 13
The XMLHttpRequest ObjectThe XMLHttpRequest ObjectreadyState property
Contains the ongoing state of the current response
Generally you want to perform a task when the response has been received (request complete)
04/21/23 Wendi Jollymore, ACES 14
StateState DescriptionDescription
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
The XMLHttpRequest ObjectThe XMLHttpRequest Object
responseText propertyContains the server’s response as textTo grab the response as XML data, use responseXML property
open(method, URL, asyncFlag) methodUsed to “open” the object and configure the request
04/21/23 Wendi Jollymore, ACES 15
Parameter What It Means
method The HTTP method used to open the connection, such as GET or POST.
URL The requested URL.
asyncFlag A Boolean value indicating whether the call is asynchronous. The default is true.
getcompa
The XMLHttpRequest ObjectThe XMLHttpRequest Object
send(info) methodSends the request to the serverFor GET requests, use the argument nullFor POST requests, you’ll need to send along information about the request
E.g. a parameter string
04/21/23 Wendi Jollymore, ACES 16
getcompa
04/21/23 Wendi Jollymore, ACES 17
Making an AJAX ExampleMaking an AJAX Example
function getData(dataSource, divID){ if(xmlHttp) { var obj = document.getElementById(divID); xmlHttp.open("GET", dataSource); xmlHttp.onreadystatechange =
function() { // we’ll fill this in later};
xmlHttp.send(null); }}
04/21/23 Wendi Jollymore, ACES 18
Making an AJAX ExampleMaking an AJAX Example
Writing the anonymous function:If the state of the response is 4
Response completed
Then:Grab the response textPlug it into the div tag
xmlHttp.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4) { obj.innerHTML = xmlHttp.responseText; }};
04/21/23 Wendi Jollymore, ACES 19
Making an AJAX ExampleMaking an AJAX Example
Save your Javascript file as ajax.jsIn your XHTML file, go to the button element in the form tagAdd an onClick=“” event:
Make sure where I have ‘display’ you put the value of your <div> id attributeCheck that your path to the data file is correct
<input type="button" value="Click Me!" onClick="getData('http://localhost/webtech/week12/example1/example1.dat‘,'display')" />
ExerciseExercise
Modify the existing example3 buttons with different captions3 different text filesMake each button display a different text file from the server
04/21/23 Wendi Jollymore, ACES 20
04/21/23 Wendi Jollymore, ACES 21
Getting a Response from PHPGetting a Response from PHP
Create a new folder for a new exampleAdd an index.html file
Form tag (no attributes required)Text fieldNamed <div> tag
Add display.phpGet the value from the text field using isset() (“Error” if no name)Echo some kind of message using the name
Copy over your ajax.js fileYou’ll be changing this a bit
04/21/23 Wendi Jollymore, ACES 22
Getting a Response from PHPGetting a Response from PHP
Modify your ajax.js code:The getData() method should accept an additional parameter for the text field name, and change the data source param to a file string for php file name:
function getData(txtField, file, divID)
Add a statement to get a reference to that text field object:
var txt = document.getElementById(txtField);
Create a url string that includes the PHP file name and the delimited parameter for the text field:
var url = file + "?txtName=" + txt.value;
Update the open statement so that your url is passed in:
XMLHttpRequestObject.open("GET", url);
04/21/23 Wendi Jollymore, ACES 23
Getting a Response from PHPGetting a Response from PHP
In the button’s onClick event:Call the getData method, and pass in the name of the text field, the name of the php file, and the name of the div tag:
<input type="button" value="Submit" onClick="getData('txtName', 'display.php', 'display');" />
04/21/23 Wendi Jollymore, ACES 24
Sending Data Using PostSending Data Using Post
Post data is encryptedUpdating your AJAX script to send via post is not easy!For explanation, see Books24x7:
Ajax for Dummies by Steve Holzner
ISBN:9780471785972 Chapter 3 – the last section (“Passing Data
to the Server with POST”)
04/21/23 Wendi Jollymore, ACES 25
Sending Data Using PostSending Data Using Post
Thankfully, Dan has given us a nice class we can use!ajax_queue.js
You can use this in the rest of today’s lesson and in your final project!
It also has a much nicer way to create the right XMLHttpRequest object for multiple browser versions!
04/21/23 Wendi Jollymore, ACES 26
Using ajax_queue.jsUsing ajax_queue.js
SimpleAJAXCall(url, callback, method, param)url:
The URL/file that should will handle the request (e.g. process a form)
callback:The name of the function that should execute upon completion of the requestE.g. your onreadystatechange function
method:GET or POST (as a string)
param:Optional – any data that needs to be passed into your callback function
04/21/23 Wendi Jollymore, ACES 27
Using ajax_queue.jsUsing ajax_queue.js
Create an index.php page:Add echo statements to include two javascript files:
A new version of ajax.jsThe ajax_queue.js library
Add statements to include your info.php file (or use variables to set up host, user, password) and database name (Media)Code to body to connect to database and select all records from Cds table, ordered by titleAdd a header for the page, and a form tagIn the form, code a list box that lists each title, but each option’s value is the id field value (next slide)Add a button “View” to the formAdd a named <div> tag under the form tag
04/21/23 Wendi Jollymore, ACES 28
Using ajax_queue.jsUsing ajax_queue.js
$numRows = mysql_num_rows($result);
echo "<p><select id='lstTitles' name='lstTitles'>\n";
for($i=1; $i<=$numRows; $i++) {
$record = mysql_fetch_array($result);
echo "<option value='".$record["id"]."'>".$record["title"]."</option>\n";
}
echo "</select></p>\n";
04/21/23 Wendi Jollymore, ACES 29
Using ajax_queue.jsUsing ajax_queue.js
The View button’s onClick event will work like before
It will call a method called getCdData()This will be defined in your brand new ajax.js file
Parameters for getCdData:The name of the list box objectThe name of the php file that will look up the CD information (viewCd.php)The name of the div tag
04/21/23 Wendi Jollymore, ACES 30
Using ajax_queue.jsUsing ajax_queue.js
Create a new ajax.js file from scratchAdd the getCdData function with three string params:
Name of list boxName of php file that will perform processing on serverName of div tag
Add the two statements that grab objects for the list box and div tag
04/21/23 Wendi Jollymore, ACES 31
Using ajax_queue.jsUsing ajax_queue.js
ajax.js file, continued:In the getCdData() method, continued:
Define a callback function that displays the result in the div tag:
var callbackFunction = function(result) {
divObj.innerHTML = result;
};
Note the parameter, and the use of it in the function!
04/21/23 Wendi Jollymore, ACES 32
Using ajax_queue.jsUsing ajax_queue.js
ajax.js file, continued:In the getCdData() method, continued:
Build the url with the parameters:var url = file + "?cdId=" + listObj.value;
Note that even though this looks like a GET way of doing things, we aren’tThe functions in side ajax_queue.js will strip off the name=value pairs and send the request using POST
This was the hard part we don’t have to worry about!
04/21/23 Wendi Jollymore, ACES 33
Using ajax_queue.jsUsing ajax_queue.js
ajax.js file, continued:In the getCdData() method, continued:
Invoke the SimpleAJAXCall() method:
SimpleAJAXCall(url, callbackFunction, "POST");
04/21/23 Wendi Jollymore, ACES 34
Using ajax_queue.jsUsing ajax_queue.js
Lastly, create the viewCd.php file:Strip out all the XHTML structureAdd the following code:
Require any info you need for database connectionGrab the cd id value using $_POST and isset()If the ID is 0 or less, display an error message, otherwise:Connect to CDs table on Media databaseSelect * from Cds where id = the id value you grabbed from $_POSTEcho a formatted string of all the fields in the found recordRemember this will go in a <div> so you don’t need structure tags here
04/21/23 Wendi Jollymore, ACES 35
Next WeekNext Week
Quiz on PHP, MySql, Ajax!10% of final gradeQuiz starts promptly at 2pm
30 minutes longBE ON TIME!!Will be graded during class, so no late/missed quizzes allowed
Rest of class is for final project work