• Hi All

    I hope you can help.
    I’m writing my first ajax call using wp_ajax and it’s just returning 0.
    My code is…

    function removeItems(){
    echo "hello";
    die();
    }
    
    add_action('wp_ajax_removeItem', 'removeItems');
    add_action('wp_ajax_nopriv_removeItem', 'removeItems'); 
    
    function remove_item(){
      echo '<script type="text/javascript">
        jQuery(document).ready(function(){
            jQuery("body").delegate(".remove_one","click",function(){
                var cart_key = jQuery(this).data("cart_key");
                jQuery.ajax({
                    type:"POST",
                    url: "/wp-admin/admin-ajax.php",
                    data: {action: "removeItem"},
                    success:function(data){
                        alert(data);
                    }
                });
            });
        });
    </script>';
    }
    
    add_action('wp_head', 'remove_item');

    The common error I can find is not including:

    add_action('wp_ajax_nopriv_removeItem', 'removeItems');

    …but I’ve added that in.

    action=removeItem

    is being added in the console.

    I know this is basic but any help would be much appreciated.
    Mark

Viewing 1 replies (of 1 total)
  • 1. Your ajax data is incorrect. You have to pass the variable.. not the entire function.
    data: {myVar: 'cart_key'},

    2. You are missing the action variable. That is what is used to match the function name that process the ajax request:

    action: 'remove_item',

    3. Your function name to process the data, and the name in the filters is inconsistent; and you need to echo a json response.

    function removeItems(){
    
        $return =  "hello";
    
        // Return response
        $response = json_encode(array('return' => $return));
        header( "Content-Type: application/json" );
        echo $response;
    
        die();
    }
    add_action('wp_ajax_rremove_item', 'removeItems');
    add_action('wp_ajax_nopriv_remove_item', 'removeItems');

    Then, you can access the response back in your javascript using:

    success:function(data){
        alert(data->return);
    }

Viewing 1 replies (of 1 total)

The topic ‘Basic ajax returning 0’ is closed to new replies.