我創建了一個簡單的聯繫我們表單,它從文本字段捕獲數據,然後將數據轉換爲JSON對象並使用Ajax發送到服務器。但我總是得到錯誤。成功功能不起作用。我相信它沒有連接到服務器。Ajax請求無效。沒有連接到服務器
請告訴我哪裏出了問題。
HTML
body>
<h1> Contact Us </h1>
We value your feedback. Send in your questions, suggestions, ideas to help us improve our service.
<h2 align="Center"> Search us on Google Maps</h2>
<br>
<br>
<form action="contact.php" name="form" method="post">
<br>Name :<br>
<input type="text" name="fName" id="fName" required >
<input type="text" name="lName" id="lName" required >
<br> <br>
Email: <br>
<input type="email" name="email" id="email" required >
<br> <br>
Comment: <br>
<textarea name= "comment" id = "comment" rows="8" cols="50" ></textarea>
<br> <br>
Rate our Website <select name="select" id="select" >
<option value = "1" name= "rate"> 1 </option>
<option value = "2" name= "rate"> 2 </option>
<option value = "3" name= "rate"> 3 </option>
<option value = "4" name= "rate"> 4 </option>
<option value = "5" name= "rate"> 5 </option>
</select>
<br> <br>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
的Javascript
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
var jsonArr = {
firstName :document.getElementById("fName").value,
lastName :document.getElementById("lName").value,
email :document.getElementById("email").value,
comment :document.getElementById("comment").value,
rate :document.getElementById("select").value
};
$.ajax({
url : "contact.php",
type : "POST",
data : JSON.stringify(jsonArr),
dataType : "json",
success : function(data){
console.log("This is working", data);
},
error : function (error){
alert("Error. not working"+ error);
console.log("Error. not working" , error);
}
});
});
});
</script>
PHP
<html>
<body>
<?php
$decode = $_POST['firstName'];
var_dump($decode);
?>
</body>
</html>
請注意,你沒有在'contact.php'文件關閉你的'php'碼 - 因此,PHP文件打印錯誤你的jscript不能訪問它。 修復:'var_dump($ decode); ?>' 另一件事 - 學會使用**螢火蟲或Chrome控制檯**,在'網絡tab'你才能真正瞭解和理解發生了什麼事情。 –
你也應該把錯誤放在alert - > alert(「Error:」+ error)中; – greenhoorn
我已經糾正了一切,但我得到的是注意:未定義的索引:firstname在C:\ xampp \ htdocs \ contact.php在線5 NULL –