Skip to content

Instantly share code, notes, and snippets.

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 leogopal/ea36473e39eb6a648c02 to your computer and use it in GitHub Desktop.
Save leogopal/ea36473e39eb6a648c02 to your computer and use it in GitHub Desktop.
WordPress Ajax
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
//functions.php code
function myFunction() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$temp = $_REQUEST['temp'];
echo "<h1>$temp</h1>";
}
die();
}
add_action('wp_ajax_myFunction' , 'myFunction'); // this is for people who are logged in
add_action("wp_ajax_nopriv_myFunction", "myFunction"); // this is for people who are not logged in
// whatever.js code -
jQuery(document).ready(function($) {
jQuery('.entry-content').append('<input id="boom"></input><p id="resp"></p>');
jQuery(document).on('change', '#boom', function(event) {
event.preventDefault();
jQuery.ajax({
url: ajaxurl, //key variable that is set in the php enqueue
type: 'POST',
data: {
'action':'myFunction', //myFunction needs to match the function in the php file as well as the add_action for it
'temp' : jQuery(this).val()
},
})
.done(function(data , status) {
//status is the http request status - 200 for all good, 404 not found e.t.c
jQuery('#resp').html(data);
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment