Created
February 29, 2016 10:24
-
-
Save leogopal/daa95aebc83392fad91f to your computer and use it in GitHub Desktop.
WordPress Ajax example
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 | |
add_action('wp_head','pluginname_ajaxurl'); | |
function pluginname_ajaxurl() { | |
?> | |
<script type="text/javascript"> | |
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; | |
</script> | |
<?php | |
} | |
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 |
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(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