[英]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.