WordPress.org

Ready to get started?Download WordPress

Forums

AJAX returning 0 (5 posts)

  1. bmd91
    Member
    Posted 1 year ago #

    I am trying to do a basic ajax function but all I can get back is a 0. Code is as follows:

    In my main script.js file I have:

    function populateCardAmount(){
        var cardAmt = $("#trading_card_amount").val();
            $.ajax({
                type: 'POST',
                url: '/wp-admin/admin-ajax.php',
                data: {
                    action: 'populate_qualified_cards',
                    cardAmt: cardAmt,
                },
                success: function(data){
                    console.log(data);
                },
                error: function(){
                    alert('error');
                }
            });
    }

    And in functions.php I have:

    function populate_qualified_cards(){
        $amt = $_POST['cardAmt'];
        print_r($amt);
        die();
    }
    add_action( 'wp_ajax_nopriv_populate_qualified_cards', 'populate_qualified_cards' );
    add_action( 'wp_ajax_populate_qualified_cards', 'populate_qualified_cards' );

    Help Please!!! Thank you!!

  2. bmd91
    Member
    Posted 1 year ago #

    Also, the js function is being called on pageload:

    $(document).ready(function(){
    	$("#trading_card_amount").keyup(populateCardAmount);
    });
  3. Did you ever find anything out on this? I'm in the same predicament.

  4. bmd91
    Member
    Posted 1 year ago #

    Make sure ajax action matches first param of add_action in functions.php. And second param matches function name, but call both params different names. And I had to direct back an additional folder to admin-ajax

  5. Hey.. thanks for posting back so quick!!

    I actually found that you must add the add_action bit to the top level of the plugin.

    I had it nested inside my admin_menu hook, which didn't work. Moving it up one level to the construct, solved the issue.

    Man... I LOVE AJAX!!

    Again, thanks for the help!!

Topic Closed

This topic has been closed to new replies.

About this Topic