How to send ajax request in wordpress without displaying zero

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 zero. I tried die (); to remove zero. But after calling this screen, the entire 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 this situation?

0
source share
1 answer

This is because your actions are not being called.

You need to declare a property actionas shown below so that WP knows which action to invoke.

ans_name ( data), $_POST['ans_name'] . , , AJAX - , $_POST['ans_name'] . , - , , .

, WP AJAX, WP, AJAX.

<script type="text/javascript">
    function key_press(){

        var data = {
            url:        '<?php echo get_admin_url()?>admin-ajax.php',
            type:       'POST',
            action:     jQuery('[name="ans_name"]').serialize(),
            ans_name:   jQuery('[name="ans_name"]').serialize()
        };

        var myRequest = jQuery.post(ajax_object.ajaxurl, data, function(response){
            alert('Got this from the server: ' + response);
        });

        myRequest.done(function(){
            alert("success");
        });

    }
</script>   

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();  // Required for a proper Wordpress AJAX result

}

, AJAX ( nopriv) , functions.php.

<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
    <script type="text/javascript">
        var ajax_object = {};
        ajax_object.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
<?php
}
?>
+3

All Articles