Skip to content

Instantly share code, notes, and snippets.

@arvindr21
Forked from devinsays/example-ajax-enqueue.php
Created October 18, 2019 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arvindr21/258cc76ccbc3898d1046e88ef4dc3f24 to your computer and use it in GitHub Desktop.
Save arvindr21/258cc76ccbc3898d1046e88ef4dc3f24 to your computer and use it in GitHub Desktop.
Simple WordPress Ajax Example
<?php
function example_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'example-ajax-script',
get_template_directory_uri() . '/js/simple-ajax-example.js',
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'example-ajax-script',
'example_ajax_obj',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
<?php
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment