我是使用 PHP 的新手。我正在實作一個包含在谷歌驗證碼函式中的電子郵件訂閱表單。我正在使用 ajax 來呼叫服務器端代碼。我遇到的問題是,當函式正確執行時,ajax 中的 success() 方法沒有被呼叫。
一些細節:第 3 方電子郵件訂閱回傳一個帶有單個鍵值對的 json 物件,{message: "you've been added"} 或 {message:"error,try again"}
如果我們點擊 php 檔案中的 else 子句,該函式就運行成功了。發生這種情況時,它會出于某種原因運行 error() 回呼嗎?即使我的狀態為 200
我懷疑我沒有回傳有效的 json 或其他東西?提前致謝!
這是我的 JS
$(".subscribe-form").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var formAction = form.attr("action");
var formMethod = form.attr("method");
var formResponse = $("#form-response");
grecaptcha.ready(function () {
grecaptcha
.execute("6Lcgdq4UAAAAAFjthnpc_WQ4leumC1UmlyLk0OwR", {
action: "submit",
})
.then(function (token) {
var recaptchaResponse = document.getElementById("recaptchaResponse");
recaptchaResponse.value = token;
$.ajax({
url: "/wp-content/themes/hello-elementor/submit.php",
type: "POST",
data: formData,
dataType: "json",
success: function (data) {
console.log(data);
if (data.error) {
formResponse.html(data.error);
} else {
formResponse.html(data.success);
}
},
error: function (data) {
console.log(data);
formResponse.html("Error, please try again");
},
});
});
});
});
這是我的 sumbit.php - 由于顯而易見的原因,我洗掉了這個秘密。
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$ttrurl = "https://3rdpartysubsciptionservice/addEmailDetails.aspx?first_name=$fname&last_name=$lname&email=$email";
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => "secret_code",
'response' => $_POST['recaptcha_response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$res = json_decode($response, true);
// Take action based on the score returned
if ($res['success'] == false && $res['score'] <= 0.5) {
// Score less than 0.5 indicates suspicious activity. Return an error
$error = "Something went wrong. Please try again later";
$output = array("error" => $error, "success" => "");
http_response_code(400);
echo json_encode($output);
} else {
// This is a human. Insert the message into database OR send a mail
$curl = curl_init();
curl_setopt_array($curl, array(CURLOPT_URL => $ttrurl));
$ttrres = curl_exec($curl);
curl_close($curl);
$message = json_decode($ttrres, true);
$output = array("error" => "", "success" => json_encode($message));
http_response_code(200);
echo json_encode($output);
}
?>
uj5u.com熱心網友回復:
請注意,您在 ajax 中設定了dataType: "json"并且您的回應似乎不是 json。在您的 php 代碼之上使用此代碼:
header('Content-Type: application/json; charset=utf-8');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443822.html
標籤:javascript php 阿贾克斯
上一篇:突出顯示搜索關鍵字
