Ensure jquery is activated
In your function that hooks “wp_enqueue_scripts”, add this:
//********** ENSURE jQuery IS ALWAYS LOADED ON PAGES **********
//(we use in our custom code)
add_action( 'wp_enqueue_scripts', 'MyThemeEnqueueScripts' );
function MyThemeEnqueueScripts()
{
wp_enqueue_script( 'jquery' );
}
add_action( 'admin_enqueue_scripts', 'MyAdminEnqueueScripts' );
function MyAdminEnqueueScripts( $hook )
{
wp_enqueue_script( 'jquery' );
}
Simple Working Example
In functions.php
add_action ( 'wp_ajax_my_ajax_action_callback', 'my_ajax_action_callback' ); //For AJAX calls made for logged in users
add_action ( 'wp_ajax_nopriv_my_ajax_action_callback', 'my_ajax_action_callback' ); //For AJAX calls made from non logged in users (include both if both logged in and not logged in users will trigger this)
function my_ajax_action_callback()
{
//Check the nonce
check_ajax_referer('my-nonce-special-string', 'security'); //This will die(); if the nonce check fails
//if (!is_user_logged_in())
// die();
//$user_id = get_current_user_id(); //Use this if your function wants the wordpress user_id (secure method, don't pass it as an ajax argument)
$ajax_value1 = 1234;
$ajax_value2 = sanitize_text_field($_POST['my_value_1']);
$ajax_value3 = 'abcd';
$ReturnArray = array(
"ajax_value1" => $ajax_value1,
"ajax_value2" => $ajax_value2,
"ajax_value3" => $ajax_value3
);
echo json_encode($ReturnArray);
wp_die(); //Terminate immediately and return a proper response
}
In your php (html) page
$AjaxUrlHtml = "var ajaxurl = '" . admin_url('admin-ajax.php') . "';";
$AjaxNonce = wp_create_nonce( 'my-nonce-special-string' );
$HtmlOutput .= <<<_END
<script type="text/javascript" >
$AjaxUrlHtml
var Counter = 0;
setInterval(function()
{
var post_data = {
'action': 'my_ajax_action_callback', //The name of the ajax callback action in functions.php
'security': '$AjaxNonce',
'my_value_1': 9876
};
jQuery.post(ajaxurl, post_data, function(response) {
//----- CALLBACK SUCCESS - RESPONSE RECEVIED -----
response = jQuery.parseJSON(response); //Decode the json response
Counter++;
document.getElementById('ajax_value1').innerHTML = Counter + '-' + response.ajax_value1 + '-' + response.ajax_value2 + '-' + response.ajax_value3;
});
}, 1000); //<<<<Call every time in mS
</script>
<p>AJAX Output: <span id='ajax_value1'>Retreiving...</span></p>
_END;
