Last active
August 29, 2015 14:00
-
-
Save nickpelton/11147744 to your computer and use it in GitHub Desktop.
WP: AJAX in WordPress - 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ = 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