180 likes | 426 Views
Ajax. CSCI 216 Tina Ostrander. What is Ajax?. AJAX = Asynchronous JavaScript and XML A technique for creating fast and dynamic web pages Allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes
E N D
Ajax CSCI 216 Tina Ostrander
What is Ajax? • AJAX = Asynchronous JavaScript and XML • A technique for creating fast and dynamic web pages • Allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes • Makes it possible to update parts of a web page, without reloading the whole page
Ajax & jQuery • jQueryprovides a rich set of methods for Ajax web development • jQuery Ajax allows you to request data from a remote server using GET or POST • TXT • HTML • XML • JSON • You can load remote data directly into selected elements of your web page!
jQuery post() method • The jQuery$.post() method loads data from the server using an HTTP POST request. • Syntax $.post(URL, {data}, function(data){…}); $.post("myScript.php", {name:txt}, function(result) { $("span").html(result); }); http://www.w3schools.com/jquery/ajax_post.asp
Example product_lookup.html <h2>Product Info</h2> <label>Enter a Product ID: <input type='text' id='id'></label> <button id='show'>Show Details</button> <div id='detail'></div>
Example - the jQuery <script src="http://code.jquery.com/jquery.js"></script> <script> $('#show').click(function(){ varprodId= $('#id').val(); $.post( "show_product.php", {id:prodId}, function(result) { $('#detail').html(result); } ); }); </script> When the button is clicked Get the text box value Ajax POST Name of the PHP script The key/value to be passed Update the "detail" div With the output of the PHP script product_lookup.html
Example - the PHP show_product.php <?php $id = $_POST['id']; mysql_connect("localhost", "omuser", "omuser") or die("Error connecting"); mysql_select_db("om") or die("Error selecting DB"); $query = "SELECT * FROM items WHERE item_id = '$id'"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) { echo "Product ID $id not found."; return; } $row = mysql_fetch_array($result); echo "<strong>Item ID:</strong> {$row['item_id']}<br>"; echo "<strong>Title:</strong> {$row['title']}<br>"; echo "<strong>Artist:</strong> {$row['artist']}<br>"; echo "<strong>Price:</strong> {$row['unit_price']}<br>"; Get this from the Ajax call
jQuery load() method • The jQuery load() method is a simple Ajax function • Syntax: • $(selector).load(url,data,callback) • Components • selectordefines the HTML element(s) to change • urlspecifies a web address for your file • data is used to send data to the server • callback is used to trigger a function after completion
<html> <body> <h2>Show me a phrase</h2> <button id="button">Go!</button><br><br> <div id="phrase"></div> </body> <script src="http://code.jquery.com/jquery.js"></script> <script> $("#button").click(function(){ $("#phrase").load('text.txt'); }); </script> </html> showphrase.html Loadinga Text File
phrase2.php <?php $adjs = array("funny", "smart", "talented", "nerdy", "gifted"); $names = array("Alissa", "Dereje", "Thuy", "Melanie", "Paul"); $name = $names[rand(0, count($names)-1)]; $adj = $adjs[rand(0, count($adjs)-1)]; $phrase = "<h3>$name is very $adj.</h3>"; echo $phrase; ?> Loadinga PHP Script
<html> <body> <h2>Show me a phrase</h2> <button id="button">Go!</button><br><br> <div id="phrase"></div> </body> <script src="http://code.jquery.com/jquery.js"></script> <script> $("button").click(function(){ $("#phrase").load('phrase.php'); }); </script> </html> showphrase2.html Loadinga PHP Script
Passing Data • $("#phrase").load('phrase.php', {name: 'Ryan'} ); • $("#phrase").load('phrase.php', {first: 'Ray', last: 'Kim'} ); • $("#phrase").load('phrase.php', {name: $("#name").val()} ); The value of the element with id=‘name’ gets passed to phrase.php as $_POST[‘name’] The output of the phrase.phpscriptgets loaded into the element with id=‘phrase’ By default, data is passed by the POST method.
phrase3.php <?php $adjs = array("funny", "smart", "talented" …); $names = array("Cheryl", “Kelly", “Ying"...); if(isset($_POST['name'])) $name = $_POST['name']; else $name = $names[rand(0, count($names)-1)]; $adj = $adjs[rand(0, count($adjs)-1)]; $phrase = "<h3>$name is very $adj.</h3>"; echo $phrase; ?> showphrase3.html <body> <h2>Enter a name: </h2> <input type='text' id='name' > <div id="phrase"></div> </body> <script src="http://code.jq..."</script> <script > $("#name").blur(function(){ vartxtName = $("#name").val(); $("#phrase").load('phrase3.php', { name: txtName} ); }); </script> id=‘name’ id=‘phrase’
Practice • Create a PHP script that defines an associative array with several (at least three) words and their definitions. • Create an HTML page that contains a drop down list and a Submit button. Populate the drop down list with your words. • When the user clicks the button, use Ajax to pass the selected word to the PHP script and display the definition. • See http://ned.highline.edu/~tostrander/216/ajax/define.html for an example
jQuery Data Tables • Copy the table source code at http://ned.highline.edu/~tostrander/216/ajax/datatables.html • Add the following to your page (jQuery at the bottom) • Reload the page! • Visit https://datatables.net/ for full documentation <link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.0/css/jquery.dataTables.css"> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script src="http://cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script> <script> $('#example').dataTable(); </script>
Web Services http://ned.highline.edu/~tostrander/216/ajax/rotten.html Documentation at http://developer.rottentomatoes.com/docs
Challenge • Create a copy of the previous example called city.html • Modify the code lookup cities, using the GeoNames API • Update the source in the autocomplete: source: function(request, response) { $.getJSON("http://api.geonames.org/searchJSON?", { name_startsWith: request.term, username: "Hannah_Ostrander", maxRows: 10 }, function(data) { // data is an array of objects vararray = data.error ? [] : $.map(data.geonames, function(m) { return { label: m.name + ", " + m.countryName }; }); response(array); }); } Documentation at http://www.geonames.org/export/web-services.html
Resources • jQueryAjax Methods Reference • jQuery Ajax Example • jQuery Ajax Tutorial