2017-10-21 46 views
1

我想通過使用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')"); 
    } 
} 
?> 

對不起,如果這種類型的問題已被問到。

+2

代碼縮進使代碼可讀 –

+0

@JaromandaX對不起,長代碼 – Nawaraj

+1

長代碼是相當好的......但缺乏縮進使代碼難以閱讀 - 當然,你不寫這樣的代碼? –

回答

0

你是不是送msgSent屬性,根據這條線在您的JS:

var dataString = 'content='+ textcontent; 

我只能看到content,你將能夠通過$_POST['content']使用。

試試這個:

var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>'; 
0

你必須通過msgSend參數根據您的實施MsgInsert.php像這樣:

$("#msgBtn").click(function() { 
    var textcontent = $("#msgInput").val(); 

    if (textcontent == '') { 
     alert("Enter some text.."); 
     $("#msgInput").focus(); 
    } 
    else { 
     var dataString = 'content=' + textcontent + '&msgSend=1'; 
     $.ajax({...}); 
    } 
}); 

始終保存用戶產生時通過即prepared statements想到escaping內容內容到您的數據庫,以避免SQL注入!