Submitting a form with ajax in Wordpress

2020-05-19 02:19发布

I am trying to get the results of an ajax request in wordpress, but I am getting result of '0' in an alert box of javascript, so the form looks like this:

<form class="form" id="ajax-contact-form" action="#">                            
        <input type="text" name="name" id="name"  placeholder="Name" required="">
        <button type="submit" class="btn">Submit</button>
</form>

The javascript looks like this:

$('#ajax-contact-form').submit(function(e){

    $.ajax({ 
         data: {action: 'contact_form'},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              alert(data); // This prints '0', I want this to print whatever name the user inputs in the form. 

        }
    });

})

And the PHP:

add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');

function contact_form()
{
echo $_POST['name'];    
}

Does anyone know if the code above is correct, I have also tried $_REQUEST['name'] and it doesnt work.

Thanks soo much,

2条回答
太酷不给撩
2楼-- · 2020-05-19 02:42

You should add an attribute for name too in your javascript.

It may look like this........

$('#ajax-contact-form').submit(function(e){

$.ajax({ 
     data: {action: 'contact_form', name:name},
     type: 'post',
     url: ajaxurl,      
     success: function(data) {
          alert(data); 
    }
});

})

查看更多
可以哭但决不认输i
3楼-- · 2020-05-19 02:53

Try something like this, you did not add the name parameter you are expecting in your PHP contact_form function, so you must add it to the data attribute in the jQuery ajax function call.

$('#ajax-contact-form').submit(function(e){
    var name = $("#name").val();
    $.ajax({ 
         data: {action: 'contact_form', name:name},
         type: 'post',
         url: ajaxurl,
         success: function(data) {
              console.log(data); //should print out the name since you sent it along

        }
    });

});
查看更多
登录 后发表回答