Last active
August 29, 2015 13:57
-
-
Save denishvachhani/9801853 to your computer and use it in GitHub Desktop.
Wordpress -- Simple Ajax Example
This file contains hidden or 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 | |
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' ); | |
?> |
This file contains hidden or 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
<div id="ajax-link">ClickHere</div> | |
<div class="ajax-content"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a basic example of how to use AJAX in WordPress. It shows how to take a variable from javascript, pass it to a PHP function (altering it slightly), and then pass it back to the javascript.
This assumes you already know how to enqueue javascript, etc.