11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 22 • CREATING AJAX-ENHANCED FEATURES WITH JQUERY AND <strong>PHP</strong>Listing 22-3. Integrating Ajax into the Username Validation Featuregoogle.load("jquery", "1.4.2");});});$(document).ready(function(){// Attach a click handler to the Check Username button$('#check_un').click(function(e) {// Retrieve the username field valuevar username = $('#username').val();// Use jQuery's $.get function to send a GET request to the available.php script// and provide an appropriate response based on the outcome$.get("available.php",{username: username},function(response){if (response.status == "FALSE") {$("#valid").html("Not available!");} else {$("#valid").html("Available!");}},"json");// Use jQuery's preventDefault() method to prevent the link from being followede.preventDefault();Like the <strong>PHP</strong> script presented in Listing 22-2, there is little to review here because many of thesejQuery features were introduced earlier in this chapter. What is new, however, is the use of jQuery’s$.get function. This function accepts four parameters, including the name of the server-side scriptwhich should be contacted (available.php), the GET parameters which should be passed to the script (in this case a parameter named username), an anonymous function which will take as input the datareturned from the <strong>PHP</strong> script, and finally a declaration indicating how the returned data will beformatted (in this case JSON). Note how jQuery is able to easily parse the returned data using a dottednotation format (in this case determining how response.status has been set).jQuery is also capable of sending POST data to a script using its native $.post method. Consult thejQuery documentation for more information about this useful feature.447

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!