Ajax Success: description, features, instructions for use

Table of contents:

Ajax Success: description, features, instructions for use
Ajax Success: description, features, instructions for use
Anonim

Ajax Success is a means of loading data from a server into a web browser without reloading the entire page. It uses a JavaScript-based XMLHttpRequest object to send and receive information to and from the server asynchronously, in the background, without user intervention. The method has become so popular that there is hardly another application that does not use Ajax. Some examples of large scale online applications driven by Ajax Success are: Gmail, Google Maps, Google Docs, YouTube, Facebook, Flickr and more.

Cross-browser capabilities

Script selectors and operations
Script selectors and operations

Ajax stands for: A - synchronous, Javascript, A nd X ml. As you can see from the notation, the process uses JavaScript, more specifically a script called jquery.js. jQuery is a JavaScript library. The file is only 96 KB, written in JavaScript and running under the name jquery.js, which simplifies JavaScript programming by providing cross-browser capabilities for DOM element selection and manipulation, event handling, Ajax Success request, and animation.

jQuery is verypopular. In May 2015, the file is used by 64.2% of all websites. Among JavaScript libraries and frameworks, jQuery has a 95.2% market share. In other words, most developers today work in jQuery, not raw JavaScript.

JQuery benefits:

  1. Cross browser support. That is, the same jQuery code runs in different browsers: Chrome, Firefox, IE, Safari, and Opera. On the other hand, in order to provide cross-browser support in raw JavaScript, you need to check the browser and issue the appropriate codes, since different browsers (especially IE) implement functions differently.
  2. Selecting and manipulating DOM elements. "Request" refers to selecting DOM elements in a web document for subsequent manipulation.
  3. Powerful selector function to select elements based on HTML title tags, e.g. HTML ID attribute, debug, CSS class name,.error, in case of Ajax Success error.

Event handling

jQuery simplifies JavaScript event handling and has special effects and animations, adapt programming for show/hide, fade-in/fade-out, slide-in/slide-out and custom animation. Ajax Success provides a simple Ajax interface for sending asynchronous HTTP GET/POST requests and processing the response.

With jQuery, you can write a few lines of code to replace a dozen JavaScript codes and run on all browsers without having to test each one separately. Cross-browser support is especially important for production, as the user does notcan test their JavaScript codes in all browsers. Jquery Ajax Success is used by over 60% of websites on the internet.

The process assumes the user is familiar with HTML5, CSS3, and JavaScript, which are prerequisites for migrating to jQuery.

Using jQuery

JQuery has two versions. The second version does not support IE<9. Because there are still quite a few old IEs (v7, v8), the first version is much more popular on production systems.

Installation and configuration process:

  1. Download the jQuery library from the site.
  2. Copy the JavaScript file (e.g. jquery-1.xx.x.min.js) to the document root, usually under the "js" subdirectory. "min.js" is a mini production version that removes extra spaces and comments to reduce file size for faster loading.
  3. The ".js" version is used for testing and studying codes.
  4. Include in HTML document. In HTML4/XHTML1.0, you must include the attribute type="text/javascript" in the opening tag.

Alternatively, instead of serving the jquery.js server, the user can use one of the CDNs (Content Distribution Network) to serve. This will save some network traffic and probably provide a faster response. Also, loading jquery.js will be cached for reuse:

  • CDN jQuery.com;
  • Google CDN;
  • Microsoft CDN.

Some usersprefer to place JavaScripts just before the end of body() instead of a section for better speed, also load CSS before JavaScripts as it often links to CSS.

Script and operation selectors

Jquery's Ajax Success selector - the most important feature of jQuery - has a special $() syntax. It can take a tag name, an id attribute (prefixed with), or a class name (prefixed with a dot). In fact, it supports all CSS selectors.

Compared to JavaScript selector functions, jQuery is very simple and a class above. It attaches an event handler that will fire after the DOM tree has been built. The " " event is different from the JavaScript " " event, which does not wait for external links such as images to load. These codes are placed in the section before the referenced elements are created. This is common jQuery practice:

$(document).ready(handler)readyonloadready()

Example - jQuery selector and operations.

jQuery selector and operation example
jQuery selector and operation example

A query in jQuery refers to selecting elements in an HTML document for further manipulation.

Query in jQuery refers
Query in jQuery refers

For example:

  1. $(document) selects the current document.
  2. $(p)selects all.
  3. Elements (Tag-Selector).
  4. $(hello) and $(message) selects one element with attribute(ID-Selector).
  5. $(.red)selects all elements that have the class="red"(Class-Selector) attribute.

Actually $() is a shorthand (alias) for the main jQuery()functions.

Methods of managing the content of an element

The user can use function chains for "Line" and "To", since most functions return an element that is in operation. In many methods, for example html() jQuery uses the same method name for both getter and setter, differentiating its argument. For example, html() without an argument returns innerHTML.

A ready document is commonly used in jQuery, which provides a shorthand written as $(function() {…}).

Types of content control for the selected element:

  • html()- get innerHTML;
  • html(value)- set innerHTML;
  • append(value) - add innerHTML to the end;
  • prepend(value) - add before innerHTML;
  • before(element) - add element before current element;
  • after(element) - add element after current element;
  • addClass(value), removeClass(value), toggleClass(value) - add, remove or toggle attribute class value.

JQuery creates an automatic looping "Line?" and "to?", e.g. $('p') selects all elements. $('p').append(…) applies append(…) to each of the selected elements in an implicit loop.

The user can also explicitly loop through.each(function() {…}) (Line? To?) if they need to apply multiple operations to the selected elements. Inside.each - $(this) denotes the element at work.

Event handling example

This example shows how to program an event handler for actionsuser. Most jQuery code is actually dealing with event handlers for a set of selected elements.

Event Handling Example
Event Handling Example

The example illustrates the jQuery selector and built-in functions.

The example illustrates the jQuery selector
The example illustrates the jQuery selector

Sequence of actions:

  1. Select source elements via appropriate jQuery selector.
  2. Define event like mouse click, key type.
  3. Write an event handler and attach it to the source.
  4. You can attach a JavaScript event handler such as click, mouseover and submit to the selected element using jQuery methods.
  5. You can disable the default handler by returning from.click(handler).mouseover(handler).submit(handler)false.

Inside the function, $(this) refers to the current object. Although $(p) returns multiple elements (in an array), you can use the same syntax to bind an event handler to EACH elements.

Used to put a JavaScript event handler in HTML tags. The practice nowadays is to leave them outside of the HTML tags and group them in a section for better MVC design.

AJAX request and response code

AJAX request and response code
AJAX request and response code

Process continued:

jquery ajax success
jquery ajax success

To test the Success function data Ajax, run the script under a web server, eg Apache:

$(:submit) selector selects all $(:text[name="message"])select

You can use $.ajax() to send an Ajax request:

  • ajax() accepts as an argument an associative array (key-value pairs);
  • type specifies the request method, such as get or post, for Ajax post Success;
  • url specifies the URL of the action, default is the current document;
  • Data provides the query string as an associative array;
  • .done() sends back when a response with status code 200 (OK) is received. Requires a function with an HTTP response message as an argument;
  • .fail() sends back when a response is received with status code NO 200 (OK);
  • .always() sends back after.done and.fail completes. It takes the no-arg function as an argument.

JavaScript extension basics

jQuery is a JavaScript extension that is easy to understand if the user is fluent in JavaScript. He just needs to trace some jQuery operations with Firebug or web developer tools. The jQuery API is available on the developer's site.

JQuery places operations in a handlerunder that runs after the DOM tree is created but before external resources such as images are loaded, which is equivalent to placing jQuery scripts just before the close tag. This is more efficient than the JavaScript engine. You can also use multiple to register multiple handlers that will be executed in the order they were registered. JavaScript can only be used oncetimes:

$(document).ready(handler)onloadwindow.onload=handler.ready()window.onload=handler

Takes an argument, which is most often an anonymous function or a predefined function. The function has no arguments.

jquery ajax success
jquery ajax success

This is so commonly used that there is shorthand.$(document).ready(handler) $ (handler).

Iterate through selected elements

A jQuery selector can select null or DOM elements. The selected elements are wrapped inside the object, since [0], [1], … etc.

You can iterate over each of these elements:

  1. Implicit iteration using the append() function for each of the selected elements in an implicit loop.
  2. Explicit iteration through.each (function).
  3. $ (this).

Suppose the user wants to apply a series of operations to each of the selected elements, he can use iteration over the selected elements. It accepts a function as an argument, which can be either an anonymous function, a predefined function, or a variable function. Inside the function, you can use a link to an element that is in work:

.each(function) and.each()$(this).

Also, $(this) refers to the jQuery object being manipulated, it can also use this which refers to the DOM element being used. That is: $(this)[0]===this

And can apply JQuery methods like.append(),.html() before $(this) but not this. On the other hand, it can apply the DOM this operation, for example,this.id.substring(0, 5), which means the first five characters of the id attribute of the DOM element in progress.

Writing Ajax with jQuery

Ajax request is asynchronous by default. In other words,.ajax() will be released, the script won't wait for a response, but will move on to the next statement so it doesn't lock or freeze the screen.

User can write Ajax Success Json using raw JavaScript. However, jQuery makes it much easier using $.ajax settings or $.ajax URL parameters.

This setting is an object of key-value pairs.

Frequently used keys:

Request URL, which can be placed outside the settings of the last form.

  1. Type - GET or POST.
  2. Ajax data Success - Requests parameters (name=value pairs) and is expressed as an object, e.g. {name:"peter", msg:"hello"} or query string "name=peter&msg=hello".
  3. DataType - expected response data type, such as text, xml, json, script or html.
  4. Headers - object for the request header key-value pair.

Server check for Ajax Success request php has "X-Requested-With: XMLHttpRequest" request header. The server program can check if the Ajax request comes through this header, like in PHP.

Security Issues

To prevent an XSS (Cross-Site Scripting) attack, the XMLHttpRequest object can only request data from the origin server servingpage.

You need to be careful when loading the script. The HTML on the $ element downloads the data from the server and wraps the returned HTML inside the matched element. This is the easiest Ajax method to download data from the server.

Let's give an example for Ajax Success function request to HTTP server for plain text.

This example uses Ajax to send a POST request asynchronously to request a text file.

Security questions
Security questions

This is the text of the Ajax Request response:

This is the text of the Ajax Request response
This is the text of the Ajax Request response

This example runs under an HTTP server (like Apache) as it sends an HTTP request to be used as a placeholder for the response text. It also contains a hyperlink to launch an Ajax request (via the loadAjaxText() function).

Ajax request with POST parameters to PHP HTTP server to get dynamic response.

HTTP to get dynamic response
HTTP to get dynamic response

The client-side HTML contains two "s" for input and output, respectively. It also contains a hyperlink to run an Ajax Success php request (via JavaScript's loadText() function).

JavaScript function
JavaScript function

The obtained results of the script of the process of asynchronous data exchange from the web server using JavaScript confirm that even without refreshing the page, online applications work quickly and efficiently. Web applications use the request or response model from an HTML server, receiving a complete page. As a result, the user gets the resultafter pressing the button and waiting for a response from the server, pressing again and waiting for a response. Ajax performs request/response operations without requiring users to wait for responses from the server.

Popular topic

Editor's choice

  • What is a proxy server and what is it for?
    What is a proxy server and what is it for?

    The word "proxy" has ever been heard by any of us, but not everyone knows what a proxy server is and what its purpose is

  • Google Chrome not working. What to do?
    Google Chrome not working. What to do?

    So why doesn't Chrome launch when we click on its desktop icon? Google Chrome not working for several reasons

  • Recovery console. Main benefits of using
    Recovery console. Main benefits of using

    Computers are quite technically complex devices. In this regard, many users from time to time encounter failures in the operation of the operating system and other programs. In most cases, you can fix problems in a matter of minutes, especially if the computer technician has the necessary skills. If a critical failure occurs, it is recommended to use the recovery console

  • What is the cluster size?
    What is the cluster size?

    The space of any storage medium (hard drive or flash drive) is not a whole piece, but a system of memory cells called clusters

  • What is defragmentation and why is it needed?
    What is defragmentation and why is it needed?

    Modern users are often spoiled by powerful computers and inexpensive components to such an extent that they do not even know the basic concepts. That is why they often find themselves in a situation where the car begins to shamelessly “slow down” and respond with extreme reluctance to any commands. As a rule, “evil viruses” that have entered the computer are blamed for everything, but sometimes the reality turns out to be much more prosaic