360 likes | 527 Views
AJAX. Javascript 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’);. Javascript Review. Quick review of some Javascript:
E N D
Javascript 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’); Wendi Jollymore, ACES
Javascript Review • Quick review of some Javascript: • object.innerHTML property • References the contents of the tag var divObject = document.getElementById(‘display’); divObject.innerHTML = “This is some text.”; Wendi Jollymore, ACES
Javascript Review • Quick review of some Javascript: • Accessing other properties using dot notation: vardivObject = 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.asp Wendi Jollymore, ACES
What is AJAX? • AJAX: • Asynchronous Javascript And XML • Makes a web page act more like an application • Normally processing occurs when the web page causes browser to make requests from web server via http • Web server sends responses back to browser • User waits while request is sent, response received, and page reloads with response data • AJAX can work behind the scenes to pages don’t REFRESH Wendi Jollymore, ACES
What is AJAX? • AJAX technology has actually been around for a long time (1998) • Didn’t catch on until 2005: • Google Maps, Google Suggest • http://www.adaptivepath.com/ideas/essays/archives/000385.php Wendi Jollymore, ACES
AJAX Example • Check out these demos: • http://demos.openrico.org/inner_ajax_HTML • http://demos.openrico.org/complex_ajax Wendi Jollymore, ACES
How AJAX Works • AJAX uses asynchronous communication • Can communicate with server multiple times while other things are going on • Some 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 Wendi Jollymore, ACES
How AJAX Works • Using Javascript and the XMLHttpRequest object: • Javascript can request data from the server behind the scenes • The 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 server • Some code might be needed on the server to process the data before it’s passed to the Javascript code • E.g. executing a query that selects records from a database Wendi Jollymore, ACES
Making an AJAX Example • Create a folder for this example • Create a plain-text file called example.dat • Put any text in it – a sentence, some words, whatever • Create an XHTML page • Add a form (don’t worry about method/action) • Add a button (NOT a Submit button!) • Add a <div><div> with an id value! Wendi Jollymore, ACES
Making 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 it • If not, it will stay false • Javascript thinks anything that isn’t false, is true! Wendi Jollymore, ACES
Making an AJAX Example • Different browsers support the XMLHttpRequest object in different ways: • If the DOM supports it, create it • Otherwise, it must be IE so create it using an ActiveX object • (This is old!) if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } Wendi Jollymore, ACES
The XMLHttpRequest Object • This object is what handles the requests and responses behind the scenes • onreadystatechange 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 Wendi Jollymore, ACES
The XMLHttpRequest Object • readyState property • Contains the ongoing state of the current response • Generally you want to perform a task when the response has been received (request complete) Wendi Jollymore, ACES
The XMLHttpRequest Object • responseText property • Contains the server’s response as text • To grab the response as XML data, use responseXML property • open(method, URL, asyncFlag) method • Used to “open” the object and configure the request Wendi Jollymore, ACES
The XMLHttpRequest Object • send(info) method • Sends the request to the server • For GET requests, use the argument null • For POST requests, you’ll need to send along information about the request • E.g. a parameter string Wendi Jollymore, ACES
Making an AJAX Example • Writing the getData() function: 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); } } Wendi Jollymore, ACES
Making an AJAX Example • Writing the anonymous function: • If the state of the response is 4 • Response completed • Then: • Grab the response text • Plug it into the div tag xmlHttp.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4) { obj.innerHTML = xmlHttp.responseText; } }; Wendi Jollymore, ACES
Making an AJAX Example • Save your Javascript file as ajax.js • In your XHTML file, go to the button element in the form tag • Add an onClick=“” event: • Make sure where I have ‘display’ you put the value of your <div> id attribute • Check 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')" /> Wendi Jollymore, ACES
Exercise • Modify the existing example • 3 buttons with different captions • 3 different text files • Make each button display a different text file from the server Wendi Jollymore, ACES
Getting a Response from PHP • Create a new folder for a new example • Add an index.html file • Form tag (no attributes required) • Text field • Named <div> tag • Add display.php • Get 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 file • You’ll be changing this a bit Wendi Jollymore, ACES
Getting 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); Wendi Jollymore, ACES
Getting 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');" /> Wendi Jollymore, ACES
Sending Data Using Post • Post data is encrypted • Updating 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”) Wendi Jollymore, ACES
Sending 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! Wendi Jollymore, ACES
Using 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 request • E.g. your onreadystatechange function • method: • GET or POST (as a string) • param: • Optional – any data that needs to be passed into your callback function Wendi Jollymore, ACES
Using ajax_queue.js • Create an index.php page: • Add echo statements to include two javascript files: • A new version of ajax.js • The 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 title • Add a header for the page, and a form tag • In 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 form • Add a named <div> tag under the form tag Wendi Jollymore, ACES
Using 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"; Wendi Jollymore, ACES
Using 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 object • The name of the php file that will look up the CD information (viewCd.php) • The name of the div tag Wendi Jollymore, ACES
Using ajax_queue.js • Create a new ajax.js file from scratch • Add the getCdData function with three string params: • Name of list box • Name of php file that will perform processing on server • Name of div tag • Add the two statements that grab objects for the list box and div tag Wendi Jollymore, ACES
Using 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! Wendi Jollymore, ACES
Using 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’t • The 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! Wendi Jollymore, ACES
Using ajax_queue.js • ajax.js file, continued: • In the getCdData() method, continued: • Invoke the SimpleAJAXCall() method: SimpleAJAXCall(url, callbackFunction, "POST"); Wendi Jollymore, ACES
Using ajax_queue.js • Lastly, create the viewCd.php file: • Strip out all the XHTML structure • Add the following code: • Require any info you need for database connection • Grab 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 database • Select * from Cds where id = the id value you grabbed from $_POST • Echo a formatted string of all the fields in the found record • Remember this will go in a <div> so you don’t need structure tags here Wendi Jollymore, ACES
Next Week • Quiz on PHP, MySql, Ajax! • 10% of final grade • Quiz starts promptly at 2pm • 30 minutes long • BE ON TIME!! • Will be graded during class, so no late/missed quizzes allowed • Rest of class is for final project work Wendi Jollymore, ACES