Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@williamromero williamromero commented Jan 5, 2016

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

@annalinneajohansson

This comment has been minimized.

Copy link
Owner Author

@annalinneajohansson annalinneajohansson commented Mar 16, 2016

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