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.

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

Quite a few settings are available for $.ajax(), not all of which are covered here or used in this book.<br />

See http://api.jquery.com/<strong>jQuery</strong>.ajax for a full list of available settings. The most common follow:<br />

• data: This describes any data to be sent to the remote script, either as a query<br />

string (key1=val1&key2=val2) or as JSON ({"key1":"val1","key2":"val2"}).<br />

• dataFilter(data, type): This callback allows prefiltering of data <strong>and</strong> is great for<br />

sanitizing data as it comes from the remote script.<br />

• dataType: This described the type of data expected from the request. <strong>jQuery</strong> makes<br />

an intelligent guess if this is left undefined. The available types are "xml", "html",<br />

"script", "json", "jsonp", <strong>and</strong> "text".<br />

• error(XMLHttpRequest, textStatus, errorThrown): This callback is to be executed<br />

in the event of a request error. The XMLHttpRequest object, a string communicating<br />

the status of the request, <strong>and</strong> an error code are passed as arguments.<br />

• success(data, textStatus, XMLHttpRequest): This callback is to be executed if the<br />

request completes successfully. The data returned from the remote script, a string<br />

communicating the status of the request, <strong>and</strong> the XMLHttpRequest object are<br />

passed as arguments.<br />

• type: This is the type of request to send. The default is GET, but POST is also<br />

available. PUT <strong>and</strong> DELETE can be used but may not work properly in all browsers.<br />

• url: This is the URL to which the request is to be sent.<br />

To send a basic POST request to your sample script <strong>and</strong> load the results into the paragraph with ID<br />

bar, you would use the following:<br />

$.ajax({<br />

"type":"POST",<br />

"url":"ajax.php",<br />

"data":"var1=val1&var2=val2",<br />

"success":function(data){<br />

$("#bar")<br />

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

.html(data);<br />

}<br />

});<br />

After executing this code, the contents of the paragraph are replaced with the loaded information<br />

(see Figure 2-22).<br />

79

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

Saved successfully!

Ooh no, something went wrong!