Skip to content

Instantly share code, notes, and snippets.

@annalinneajohansson
Last active December 31, 2023 05:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save annalinneajohansson/6088553 to your computer and use it in GitHub Desktop.
Save annalinneajohansson/6088553 to your computer and use it in GitHub Desktop.
Basic AJAX function in WordPress
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);
});
});
<?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
}
@williamromero
Copy link

On this example... You have to create hip-ajax folder into the plugins folder, right?

@annalinneajohansson
Copy link
Author

No, hip-ajax is just the handle for the script and you can rename it into anything really.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment