我想通過使用AJAX在我的項目中實現一個消息系統,但由於我是AJAX新手,所以出現了一些問題。 下面的代碼能夠將MsgMain.php
文件的輸入數據完美地發送到MsgInsert.php
。但是,當我嘗試從MsgInsert.php
失敗。無法識別使用AJAX的HTML表單元素的值
AJAX代碼是MsgMain.php
$(document).ready(function(){
$("#chatBtn").click(function(){
$("#msgBtn").val("chat");
});
$("#pmBtn").click(function(){
$("#msgBtn").val("pm");
});
});
$(function() {
$("#msgBtn").click(function() {
var textcontent = $("#msgInput").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#msgInput").focus();
}
else
{
$.ajax({
type: "POST",
url: "msg/MsgInsert.php",
data: dataString,
cache: true,
success: function(response){
document.getElementById('content').value='';
$("#msgBtn").focus();
}
});
}
return false;
});
});
MsgMain.php
文件代碼只是HTML表單
<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
<div class="input-group ">
<input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
<div class="input-group-btn">
<button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
MsgInsert.php
文件的代碼,效果很好,當我刪除的$_POST['msgSend']
if語句
<?php
if(!isset($_SESSION['login_user'])){
header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
if (isset($_POST['msgSend'])) {
$conn = mysqli_connect("localhost", "root", "", "msg");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$content=$_POST['content'];
mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
}
}
?>
對不起,如果這種類型的問題已被問到。
代碼縮進使代碼可讀 –
@JaromandaX對不起,長代碼 – Nawaraj
長代碼是相當好的......但缺乏縮進使代碼難以閱讀 - 當然,你不寫這樣的代碼? –