php-wordpressHow to make an AJAX request in WordPress using PHP?
Making an AJAX request in WordPress using PHP is relatively easy. The following example code block shows how to make an AJAX request in WordPress using PHP:
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die(); // this is required to terminate immediately and return a proper response
}
The output of the example code is:
10
Code explanation
-
add_action( 'wp_ajax_my_action', 'my_action_callback' );- This line adds an action hook to WordPress which will trigger themy_action_callbackfunction when the AJAX request is made. -
function my_action_callback() {- This line defines themy_action_callbackfunction which will be triggered when the AJAX request is made. -
global $wpdb;- This line allows access to the WordPress database. -
$whatever = intval( $_POST['whatever'] );- This line retrieves the value of thewhateverparameter from the AJAX request. -
$whatever += 10;- This line adds 10 to the value of thewhateverparameter. -
echo $whatever;- This line prints the value of thewhateverparameter. -
wp_die();- This line is required to terminate the AJAX request and return a proper response.
Helpful links
More of Php Wordpress
- How to use get_header in WordPress using PHP?
- How to disable PHP warnings in WordPress?
- How to create a menu in WordPress using PHP?
- How to configure Nginx for WordPress?
- How to send an email using PHP in WordPress?
- How to increase the upload limit in WordPress using PHP?
- How to run an SQL query in WordPress using PHP?
- How to hide PHP warnings in WordPress?
- How to use hooks in WordPress with an example?
- How to create pagination in WordPress using PHP?
See more codes...