Created
May 6, 2015 12:23
-
-
Save yratof/ac51eef949e3c3d33ffb to your computer and use it in GitHub Desktop.
AJAX with Wordpress
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 ajax_function_for_doing_something(){ | |
echo 'This is AJAX!'; | |
die(); // All ajax functions MUST die. otherwise they never give results back | |
} | |
// Add the ajax hooks for when you're logged in | |
add_action( 'wp_ajax_DO_SOMETHING', 'ajax_function_for_doing_something' ); | |
// Add the ajax hooks for front end when not logged in | |
add_action( 'wp_ajax_nopriv_DO_SOMETHING', 'ajax_function_for_doing_something' ); | |
?> |
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="content"> | |
<span class="loading">One second, we're just loading this section for you...</span> | |
</div> | |
<script type="text/javascript"> | |
jQuery(document).ready(function($) { | |
// Start the Ajax thing here | |
$.ajax({ | |
type: 'GET', // We're "GET"ing something | |
url: '<?php echo admin_url('admin-ajax.php'); ?>', // THis is wordpress AJAX shit | |
data: { | |
'action': 'DO_SOMETHING' // this is the action at the end of the add_action thing | |
}, | |
success:function(data) { | |
// This outputs the result of the ajax request | |
//console.log('Results = ' + data); | |
$('#content').html(data); // this replaces the content within #content with the results | |
}, | |
error: function(errorThrown){ | |
console.log(errorThrown); | |
} | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment