WordPress Implements custom AJAX requests

Source: Internet
Author: User

WordPress implements AJAX requests in two situations: the AJAX request initiated by the foreground page and the AJAX request initiated by the background page.

In the data passed by Ajax, the action is a fixed field, and the value corresponding to the Action field must match the suffix in the hook name (the your_action_name part of the hook below). WordPress also takes this to differentiate between different AJAX requests.



1. Background AJAX Requests

Involves a hook:wp_ajax_ (your_action_name)

Back-end PHP code for working with Ajax

JS Code


It is noteworthy that since the beginning of WordPress 2.8, the background interface has been automatically assigned a JS global variable ajaxurl, so in the above case, JS code can directly refer to this global variable as the request path of Ajax.





2. The foreground initiates an AJAX request

Involving another hook:wp_ajax_nopriv_ (Your_action_name)



Note: Unlike the situation 1, the front-end interface does not have a direct reference to the Ajaxurl, so you must pass a WordPress function Wp_localize_script () to pass the path variable through PHP to the front-end JS, for example:

In this way, we read the object Test_ajax in the JS code Ajaxu


The object variable Test_ajax here can only be accessed by the code in the corresponding JS file, which is the script.js in the above example.

Back-end PHP code for working with Ajax

JS Code

WordPress Implements custom AJAX requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.