繁体   English   中英

无法正确处理AJAX请求发送的数据

[英]Unable to properly handle the data sent by AJAX request

我在Wordpress上有一个自定义表格(请不要建议联系表格7),该表格允许用户向慈善机构捐款。 它使用jQuery Validate插件验证数据。 一旦数据被视为有效,它将数据推送到第三方支付处理器。 这很好用,但我想将表单上的数据存储到Wordpress DB中(联系信息和捐赠价值)。

我不确定如何做到最好,而模板文件标题中的PHP将是最简单的,因为Submit操作会导致重定向,所以我认为使用AJAX是最好的选择。 我遵循了教程,现在将JSON数据发送到AJAX“处理程序”文件。 我的jQuery代码(经过验证等)如下:

console.log("Donation Type: " + donationType + " Once-off");
string = JSON.stringify(submission);
console.log(string);

jQuery.ajax({
    url : "http://192.168.8.50/subsite/wp-admin/admin-ajax.php",
    type : 'post',
    data : {
        action : 'store_donation_to_db',
        post_id : post_id,
        fields : string
    },
    success : function( response ) {
        console.log( response );
    }
});

//ProcessDonation(submission);

解释AJAX数据是我面临的问题。 我使用了以下内容:

add_action( 'wp_ajax_nopriv_store_donation_to_db', 'store_donation_to_db' );
add_action( 'wp_ajax_store_donation_to_db', 'store_donation_to_db' );

function store_donation_to_db() {
    //register log file path
    $path = plugin_dir_path( __FILE__). 'test-button-log.txt';
    //$handle = fopen($path,"w");


    // The message written to the file
    $new_line = "****************************************************************************\r\n";
    $log_entry = $_REQUEST;
    // Write the contents to the file, 
    // using the FILE_APPEND flag to append the content to the end of the file
    // and the LOCK_EX flag to prevent anyone else writing to the file at the same time
    //
    file_put_contents($path, $log_entry, FILE_APPEND | LOCK_EX);

    $variables = json_decode($_REQUEST['store_donation_to_db']);
    //file_put_contents($path, $variables, FILE_APPEND | LOCK_EX);
    $counter= 0;
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
        $string = "Hello";
        foreach($variables as $field)
        {
            $string .= $field." ".$counter;
            $counter++;
        }
        echo $string;
        die();
    }
    else {
        wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
        exit();
    }
}

我对AJAX调用只会返回“ Hello”感到沮丧,因此我添加了将$ _REQUEST数据写入文本文件的行,该数据在下面,并且看起来像JSON数组:

store_donation_to_db{\"Title\":\"Mrs\",\"FirstName\":\"Daniel\",\"Surname\":\"Holland\",\"EmailAddress\":\"daniel@dfdsfdsf.com\",\"ContactNumber\":\"\",\"DateofBirth\":\"2017-07-10\",\"undefined\":\"0\",\"recurringCHK\":\"1\",\"DonationAmount\":\"1000\"}

为什么我无法访问$ variables数组? $ _REQUEST变量不应该是既包含post_id又包含fields及其相应值的索引的数组吗? 我觉得我快要解决这个问题了,可能是我错了一条愚蠢的行(考虑到文本文件日志的准确性)。

您将AJAX与POST方法结合使用,则可以使用php中的POST全局变量访问POST数据。

$ _POST ['post_id]和$ _POST ['fields'],然后解码json字符串并将其存储在DB中。

你尝试过这个吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM