使用jQuery AJAX调用传递变量并启动PHP函数

时间:2017-06-17 22:11:50

标签: php jquery ajax wordpress

我的网站上有一个表单,如果验证失败(设置为只接受一些电子邮件顶级域名),我想将电子邮件地址保存为.txt文件。

为此,我希望包含一个AJAX调用,将电子邮件地址作为变量传递,并调用PHP函数,该函数将电子邮件地址写入文件。

它没有用,我无法理解为什么。我已将我的功能挂钩到内置的Wordpress AJAX处理程序。任何想法都非常感激。

----编辑:这现在有效-----

PHP

function text_ajax_process_request() {
    // first check if data is being sent and that it is the data we want
    if ( isset( $_POST["post_var"] ) ) {
        // now set our response var equal to that of the POST var (this will need to be sanitized based on what you're doing with with it)
        $response = $_POST["post_var"];
        file_put_contents('/home/benefacto/public_html/dev3/' . "login-error.txt", $response . ', ', FILE_APPEND | LOCK_EX);
        echo $response;
    die();
    }
}

add_action('wp_ajax_nopriv_test_response', 'text_ajax_process_request');
add_action('wp_ajax_test_response', 'text_ajax_process_request');

这是jQuery函数

function newbie(email) {
var data = {
action: 'test_response',
                        post_var: email
                        };

// This is a shortened version of: https://api.jquery.com/jquery.post/
    jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, 
    function(response) {
        alert(response);
            });
        return false;
}

这是用来调用它的jQuery

        jQuery(document).ready(function(){
        var email = 'enter email here';
        newbie(email);
        });

0 个答案:

没有答案