[英]Data is sent through Ajax request but PHP script is not receiving
我正在嘗試將表單數據發送到 php 腳本,但該腳本沒有接收到數據。
我不明白為什么,Javascript 應該沒問題 php 應該沒問題。
在 ajax 請求之前測試數據顯示結果,但從服務器端檢查 POST 數據返回空。
這是我的 ajax 代碼:
var request = $.ajax({
method: "POST",
url: 'contact-mail.php',
data: { nume: nume.value, telefon: telefon.value, email: email.value, message: message.value},
error: function(err, status) { console.log("error contact " + err);}
});
request.done(function(msg) {
alert(msg);
document.querySelectorAll(".sdc-cardboard-form input").forEach(input => {
input.value = "";
});
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
這就是我在 PHP 腳本中獲取數據的方式:
$name = $_POST['nume'];
$name = addslashes($name);
$tel = $_POST['telefon'];
$tel = addslashes($tel);
$email = $_POST['email'];
$email = addslashes($email);
$message = $_POST['message'];
$message = addslashes($message);
echo "Server side: ".$name." ".$tel." ".$email." ".$message;
Echo 僅返回“服務器端:”部分。
我正在使用相同的方法將數據發送到另一個網站上的服務器。
有人看到我的代碼中有任何錯誤嗎? 有什么我想念的嗎?
Jquery 3+
PHP 7.2
更新,問題。 會不會是 htaccess 重寫規則,它會從.php 開始修剪所有內容?
這是我的 htaccess 重寫規則:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]
我沒有閱讀太多關於 htacess 的內容,所以我只是在猜測。
由於您使用 mod-rewrite 來重定向文件擴展名,因此您需要在 AJAX 請求中執行此操作。 改變:
url: 'contact-mail.php',
至
url: 'contact-mail',
Due to .htaccess rewrite rules (Apache mod_rewrite: https://httpd.apache.org/docs/2.4/rewrite/intro.html ) all the url for those PHP files will be update
表示example.com/test.php將是example.com/test
這就是為什么您的 AJAX 請求沒有找到 URL 並給您一個錯誤的原因。
url: 'contact-mail.php'
應該是
url: 'contact-mail'
請檢查這是否有效。 如果它不起作用,請回復或評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.