2012-04-20 42 views
0

我需要使用AJAX將用戶輸入註釋立即保存到數據庫。 這是評論框。使用AJAX將數據記錄到數據庫

<div class="comment"> 
     <form action="comment.php"> 
     <textarea cols="35" name="comments"> Give us comment </textarea> 
     <input type="button" value="comment" onclick="ajaxFunction()"> 
     </form>     
</div> 

這是PHP代碼

<?php 

$link = mysql_connect("localhost","root",""); 
mysql_select_db("continental_tourism"); 

$comments = $_POST['comments']; 

if($comments == "") 
echo "Please type your comment"; 
else 
{ 
$query = "insert into comment(comment) values('$comments') "; 
mysql_query($query); 
} 
return; 
?> 

我需要知道應如何改變。 謝謝

+2

我認爲看到'ajaxFunction()'是必要的。另外,如果你想讓人們爲你丟桌子,只需要問。 SQL注入不應該是這麼簡單。請查看準備好的陳述。 – Dan 2012-04-20 01:55:59

+1

你需要發送數據在ajaxfunction() – Satya 2012-04-20 01:56:28

+0

你能包括ajaxFunction()的代碼嗎?一般來說,你可以看看像prototype或jQuery這樣的框架。 – 2012-04-20 02:00:45

回答

4

我會chnage你的HTML這樣

<textarea cols="35" id="comments"> Give us comment </textarea> 
<input type="button" value="comment" id="btnSave" /> 

和腳本

$(function(){ 
$("#btnSave").click(function(e){ 
    e.preventDefault(); 
    $.post("yourphpfile.php", { comments : $("#comments").val() } ,function(data){ 
    alert(data); 
    }); 
}); 
}); 

以上腳本將發送一個Ajax請求與存在於textarea的價值yourphpfile.php與id評論。然後一旦它從服務器頁面獲取一些數據。它只是提醒它(如果你願意,你可以在單獨的div中顯示)。將數據保存到數據庫後,您應該回顯您的php文件的響應。

由於括號已經提到過,在保存正在從查詢字符串值讀取的數據時,您應該注意SQL注入。在進行查詢之前先進行適當的衛生處理。對不起,我不是一個PHP的傢伙。所以不知道該怎麼做。

不要忘了將jQuery庫包含到您的頁面

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> 

如果遇到任何問題,您可以使用螢火蟲控制檯來調試腳本錯誤。

+0

幷包括jQuery ... – jeroen 2012-04-20 02:03:39

+0

@ jeroen:當然。 :)我會添加到答案。 – Shyju 2012-04-20 02:04:19

+0

你可以做一些簡單的事情,比如運行$ escaped_value = mysql_real_escape_string($ _ POST ['comment']);以逃避 – 2012-04-20 02:04:38

相關問題