Skip to content

Instantly share code, notes, and snippets.

@nickpelton
Last active August 29, 2015 14:00
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 nickpelton/11147744 to your computer and use it in GitHub Desktop.
Save nickpelton/11147744 to your computer and use it in GitHub Desktop.
WP: AJAX in WordPress - 2
<?php
/**
* Setup JSON Ajax endpoint for Javascript async access to WP data
*/
add_action('wp_ajax_my_action_1', 'my_callback_function_1'); // Enable for logged-in users
add_action('wp_ajax_nopriv_my_action_1', 'my_callback_function_1'); // Enable for anonymous users
function my_callback_function_1(){
header('Content-Type: text/html');
echo '<p>HTML from WP for Javascript</p>';
die(); // Prevent WP -1
}
<?php
// Setup our data
$myDataArray = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
// Pass data to myscript.js on page load
wp_localize_script( "myScript", "myLocalizedData", $myDataArray );
// wp_localize_script( $handle, $objectName, $arrayOfValues );
// $handle - The enqueued script to place the data immedietly before
// $objectName - Name of the JS object that will hold the data
// $arrayOfValues - Data to pass to JS
$ = jQuery.noConflict();
$(document).ready(function(){
/**
* Accessing data passed to JS from WP on page load
*/
// Place Data in DOM
$('#displayData').append("Ajax URL: "+myLocalizedData.ajax_url+"<br>");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment