php 在 Wordpress 中使用 ajax 提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18777728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:12:15  来源:igfitidea点击:

Submitting a form with ajax in Wordpress

phpjqueryajaxwordpress

提问by MariaZ

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:

我正在尝试在 wordpress 中获取 ajax 请求的结果,但我在 javascript 的警报框中获取结果为“0”,因此表单如下所示:

<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:

javascript 看起来像这样:

$('#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:

和 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.

有谁知道上面的代码是否正确,我也试过 $_REQUEST['name'] 但它不起作用。

Thanks soo much,

非常感谢,

采纳答案by Sterling Archer

Try something like this, you did not add the nameparameter you are expecting in your PHP contact_formfunction, so you must add it to the dataattribute in the jQuery ajax function call.

尝试这样的事情,您没有name在PHPcontact_form函数中添加您期望的参数,因此您必须将其添加到datajQuery ajax函数调用中的属性中。

$('#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

        }
    });

});

回答by Shashank Shah

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

您也应该在 javascript 中为 name 添加一个属性。

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); 
    }
});

})

})