📜 ⬆️ ⬇️

jQuery for beginners. Part 3. AJAX


I present to you the third article in the jQuery series for beginners. This time I will try to talk about the implementation of AJAX requests ...

What is AJAX, I think you should not tell, because with the advent of the web two-zero, most users are already nosy from reloading pages completely, and with the advent of jQuery, the implementation has become simpler at times ...

Note : In all examples, an abbreviated version of the jQuery method call is used using the $ (dollar sign) function

jQuery (..). load


')
Let's start with the simplest - loading HTML code into the DOM element we need on the page. For this purpose, the load method is suitable. This method can take the following parameters:
  1. url of the requested page
  2. transmitted data (optional)
  3. whose function will be fed the result (optional parameter)

I will give an example of javascript code:
// at the end of the page loading
$ ( document ) . ready ( function ( ) {
// hang on click on the element with id = example-1
$ ( '# example-1' ) . click ( function ( ) {
// load HTML code from example.html file
$ ( this ) . load ( 'ajax / example.html' ) ;
} )
} ) ;

Example of loadable data (the contents of the file example.html ):
Example <br />
Data Loaded By AJAX <br />
Bye-bye


Work example


jQuery.ajax


This is the most basic method, and all subsequent methods are just wrappers for the jQuery.ajax method. This method has only one input parameter - an object that includes all the settings (the parameters that should be remembered are highlighted):

Local AJAX Events :

To organize HTTP authorization (O_o):

Example javaScript'a:
$. ajax ( {
url : '/ajax/example.html' , // specify the URL and
dataType : "json" , // type of loaded data
success : function ( data , textStatus ) { // hang our handler on the success function
$. each ( data , function ( i , val ) { // process the received data
/ * ... * /
} ) ;
}
} ) ;



jQuery.get


Loads the page using a GET request for data transfer. It can take the following parameters:
  1. url of the requested page
  2. transmitted data (optional)
  3. callback function to feed the result (optional)
  4. data type returned in the callback function (xml, html, script, json, text, _default)


jQuery.post


This method is similar to the previous one, only the transmitted data will go to the server via POST. It can take the following parameters:
  1. url of the requested page
  2. transmitted data (optional)
  3. callback function to feed the result (optional)
  4. data type returned in the callback function (xml, html, script, json, text, _default)


Javascript:
$ ( document ) . ready ( function ( ) { // upon completion of page loading
$ ( '# example-3' ) . click ( function ( ) { // hang on the click on the element with id = example-3
$. post ( 'ajax / example.xml' , { } , function ( xml ) { // load XML from example.xml file
$ ( '# example-3' ) . html ( '' ) ;
$ ( xml ) find ( 'note' ) . each ( function ( ) { // fill the DOM element with XML data
$ ( '# example-3' ) . append ( 'To:' + $ ( this ) . find ( 'to' ) . text ( ) + '<br/>' )
. append ( 'From:' + $ ( this ) . find ( 'from' ) . text ( ) + '<br/>' )
. append ( '<b>' + $ ( this ) . find ( 'heading' ) . text ( ) + '</ b> <br/>' )
. append ( $ ( this ) . find ( 'body' ) . text ( ) + '<br/>' ) ;
} ) ;
} , 'xml' ) ; // we explicitly specify the data type
} )
} ) ;

File example.xml :

<? xml version = "1.0" encoding = "UTF-8" ?>
<note >
<to > Tove </ to >
<from > Jani </ from >
<heading > Reminder </ heading >
<body > Don't forget me this weekend! </ body >
</ note >


Work example

jQuery.getJSON


Loads data in JSON format (more convenient and faster than XML). It can take the following parameters:
  1. url of the requested page
  2. transmitted data (optional)
  3. callback function to feed the result (optional)


Javascript:
$ ( document ) . ready ( function ( ) { // upon completion of page loading
$ ( '# example-4' ) . click ( function ( ) { // hang on the click on the element with id = example-4
$. getJSON ( 'ajax / example.json' , { } , function ( json ) { // load JSON data from example.json
$ ( '# example-4' ) . html ( '' ) ;
// fill the DOM element with data from the JSON object
$ ( '# example-4' ) . append ( 'To:' + json. note . to + '<br/>' )
. append ( 'From:' + json. note . from + '<br/>' )
. append ( '<b>' + json. note . heading + '</ b> <br/>' )
. append ( json. note . body + '<br/>' ) ;
} ) ;
} )
} ) ;

File example.json :
{
note : {
to : 'Tove' ,
from : 'Jani' ,
heading : 'Reminder' ,
body : 'Don \' t forget me this weekend! '
}
}


Work example


jQuery.getScript


This function loads and executes local javascript. It can take the following parameters:
  1. url of the requested script
  2. callback function to feed the result (optional)


Javascript:
$ ( document ) . ready ( function ( ) { // upon completion of page loading
$ ( '# example-5' ) . click ( function ( ) { // hang on the click on the element with id = example-5
$. getScript ( 'ajax / example.js' , function ( ) { // loading JavaScript from example.js file
testAjax ( ) ; // execute loaded javascript
} ) ;
} )
} ) ;

File example.js :
function testAjax ( ) {
$ ( '# example-5' ) . html ( 'Test completed' ) ; // change the element with id = example-5
}


Work example


Submitting a Form


To submit the form via jQuery, you can use any of the following methods, but for the convenience of “collecting” data from the form, it is better to use the jQuery Form plugin

Sending Files


To send files via jQuery, you can use the plugin Ajax File Upload or One Click Upload

PHP interaction


To organize work with PHP I use jQuery-PHP library, it’s convenient if you like jQuery;), read more in the PHP article for jQuery

JSONP usage examples


Separately, it is worth noting the use of JSONP - for this is one of the ways to perform cross-domain data loading. If we exaggerate a little, this is the connection of remote JavaScript, which contains the necessary information in JSON format, as well as a call to our local function, the name of which we specify when accessing the remote server (usually this is the callback parameter). Slightly more clearly this can be demonstrated by the following diagram (clickable):


When working with jQuery, the name of the callback function is automatically generated for each call to the remote server; to do this, just use the GET request in the view:
  http://api.domain.com/?type=jsonp&query=test&callback=? 

Instead of the last question mark (?), The name of the callback function will be substituted. If you do not want to use this method, you will need to explicitly specify the name of the callback function using the jsonp option when calling the jQuery.ajax () method.


Google Search


An example of obtaining and processing search results using Google, for more information, see the article " jQuery + AJAX + (Google Search API || Yahoo Search API) "

Yahoo Search


An example of obtaining and processing search results using Yahoo, more information can be found in the article " jQuery + AJAX + (Google Search API || Yahoo Search API) "

JSONP API


I will also give a small list of open API with JSONP support:


Developments


For convenience of development, several event's hang on AJAX requests, they can be set for each AJAX request individually or globally. You can hang your function on all the events.

An example for displaying an element with id = "loading" during the execution of any AJAX request:
$ ( "#loading" ) . bind ( "ajaxSend" , function ( ) {
$ ( this ) . show ( ) ; // show item
} ) . bind ( "ajaxComplete" , function ( ) {
$ ( this ) . hide ( ) ; // hide item
} ) ;

For local events, we make changes to the options of the ajax () method:
$. ajax ( {
beforeSend : function ( ) {
// Handle the beforeSend event
} ,
complete : function ( ) {
// Handle the complete event
}
// ...
} ) ;


For greater clarity, give the following diagram (clickable):



Well, actually a list of all the events:

You can also download all the examples in one archive .

Cycle of articles


  1. jQuery for beginners
  2. jQuery for beginners. Part 2. JavaScript Menu
  3. jQuery for beginners. Part 3. AJAX

PS For syntax highlighting I used the mini-service http://highlight.hohli.com/

Source: https://habr.com/ru/post/42426/


All Articles