I am trying to send ajax request to another php page in wordpress. But every time it returns zero with other results.I need to remove the zero. I tried die(); to remove the zero. But after calling this, whole screen becomes blank. My code is below,
Jquery,
<script type="text/javascript">
function key_press(){
jQuery.ajax({
url : '<?php echo get_admin_url()?>admin-ajax.php',
type : 'POST',
data : jQuery('[name="ans_name"]').serialize()
}).done(function(result) {
// ta da
//alert("success");
jQuery("#widget_poll_id").html(result);
});
}
</script>
PHP,
add_action( 'wp_ajax_nopriv_'.$_POST['ans_name'], 'my_ajax' );
add_action( 'wp_ajax_'.$_POST['ans_name'], 'my_ajax' );
function my_ajax() {
echo $_POST['ans_name'];
die();
}
How could I get rid of from this situation ?
It's because your actions are not being called.
You need to declare the property
action
as below so that WP knows which action to call.In your particular case you'll also have to declare
ans_name
(as opposed todata
), so that$_POST['ans_name']
exists. I'm guessing that you wish this AJAX request to be called on many occasions by the fact that you used$_POST['ans_name']
in your hook name. If that is not the case, I suggest you use something static, as the hook could be called during other requests when you do not want it.Finally, I've retrofitted your code with the WP AJAX handler, which will ensure all of the WP goodness that you may need during an AJAX request is included.
Addition
To ensure AJAX requests for non-logged in users (the
nopriv
hook) are handeled correctly, add this to yourfunctions.php
file.