02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

To send a request with data using POST, the following code could be used:<br />

$.post("ajax.php", {"var1":"value"}, function(data){<br />

$("#bar")<br />

.css("background","yellow")<br />

.html(data);<br />

});<br />

$.getJSON()<br />

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

When loading JSON data, $.getJSON() is a shortcut function. It accepts the URL to which requests are<br />

sent, optional data, <strong>and</strong> an optional callback function.<br />

To run an example of this function, another test file needs to be created: create a new file called<br />

json.php in the testing folder, <strong>and</strong> insert the following JSON into it:<br />

{"var1":"value1","var2":"value2"}<br />

Now, load the contents of json.php <strong>and</strong> output the contents in the paragraph with ID bar:<br />

$.getJSON("json.php",<br />

function(data){<br />

$("#bar")<br />

.css("background","yellow")<br />

.html(data.var1+", "+data.var2);<br />

});<br />

Upon execution, the contents of the paragraph will be replaced with the string "value1, value2".<br />

$.getScript()<br />

To load external JavaScript, use the $.getScript() function. This accepts a URL to which the request is<br />

sent <strong>and</strong> an optional callback (which is generally not needed, as the script will execute automatically on<br />

a successful load).<br />

Create a new file called script.php in the testing folder, <strong>and</strong> insert the following:<br />

alert("This script was loaded <strong>by</strong> AJAX!");<br />

Now, load this script <strong>by</strong> executing the following code in the console:<br />

$.getScript("script.php");<br />

.load()<br />

Upon execution, the alert fires.<br />

The .load() method works just like $.get() or $.post(), except it’s a method instead of a global<br />

function. It has an implicit callback, which is to replace the HTML of the matched elements with the<br />

content returned from the remote file.<br />

The method accepts the same three arguments: destination URL, optional data, <strong>and</strong> an optional<br />

callback (which fires after the element content has been replaced).<br />

Load the contents of ajax.php in the paragraph with ID bar after sending some data using this code:<br />

83

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

Saved successfully!

Ooh no, something went wrong!