Noman
Noman

Reputation: 58

Ajax Working but empty response from AJAX in WordPress

I try to code different way but i'm facing same issue, admin-ajax working well but nothing returning, Basically empty response, I just want to what i mass up with,

My HTML Code

<form action="<?php echo home_url("/") ?>" method="post">
    <input type="text" id="noman_input" name="input_name_sb">
    <?php wp_nonce_field('sb_form');?>
    
    <input id="sub_form"  class="btn btn-danger"  type="submit" value="Post Via Ajax">
</form>

PHP Code

function form_sb_form(){
    $user_name = $_POST['input_name_sb'];
    echo $user_name;
    die();
}

add_action('wp_ajax_sb_form', 'form_sb_form');
add_action('wp_ajax_nopriv_sb_form', 'form_sb_form');

JS Code

 $("#sub_form").on('click', function(e) {
            e.preventDefault();
            var user_name = $("#noman_input").val();

            // i try with this code 
            $.ajax({
                url: loc_data.ajax_url,
                type: "POST",
                data: {
                    action: 'sb_form',
                    name: user_name
                },
                success: function(response) {
                    console.log(response)
                },
            });

            // and this one as well
            $.post(loc_data.ajax_url, {
                action: "sb_form",
                user_name: user_name,
            }, function(response) {
                console.log(response);
            });

        });

Upvotes: 0

Views: 735

Answers (1)

Ash0ur
Ash0ur

Reputation: 1545

You target the wrong $_POST key. It should be name instead of input_name_sb

function form_sb_form(){
    $user_name = $_POST['name'];
    echo $user_name;
    die();
}

Upvotes: 1

Related Questions