Last active
December 31, 2023 05:50
-
-
Save annalinneajohansson/6088553 to your computer and use it in GitHub Desktop.
Basic AJAX function in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(document).ready(function($){ | |
var ajaxurl = object.ajaxurl; | |
var data = { | |
action: 'my_action', // wp_ajax_my_action / wp_ajax_nopriv_my_action in ajax.php. Can be named anything. | |
foobar: 'some value', // translates into $_POST['foobar'] in PHP | |
}; | |
$.post(ajaxurl, data, function(response) { | |
alert("Server returned this:" + response); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// embed the javascript file that handles the AJAX vodoo | |
wp_register_script( 'hip-ajax', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) ); | |
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) | |
wp_localize_script( 'hip-ajax', 'object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); | |
wp_enqueue_script( 'hip-ajax'); | |
add_action( 'wp_ajax_my_action', 'my_action_callback' ); | |
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); // for use outside admin | |
function my_action_callback(){ | |
$foobar = $_POST['foobar']; | |
// do stuff here, for example wp_update_meta | |
echo "something"; // will be 'response' in ajax.js | |
die(); // this is required to return a proper result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No, hip-ajax is just the handle for the script and you can rename it into anything really.