使用AJAX + jQuery + PHP将数据发送到MySQL

我一整天都在寻找一种方法将一些数据插入到我的数据库中,然后在我网页上已经存在的数据列表中显示新数据。

我知道我无法完成的一些要点可能是基础知识,但我刚开始学习Javascript / AJAX,所以我的知识有限。

我认为70%的工作已完成,我可以使用AJAX / jQuery / PHP在我的网页上显示数据,但我无法想象如何再次使用AJAX / jQuery / PHP将数据从“textarea”发送到我的数据库。

到目前为止,这就是我所做的:

的index.php
在这个页面中,我想我需要在按钮上放置一个onClick:function()但我不知道该放置该函数的位置以及它应该做什么。

    TP2     Message:   

javascript.js
此页面包含在#output div中显示我的数据的AJAX代码。 我只是不知道在“data:{}”中输入什么,所以我的textarea的内容被发送到我的php文件。

 $.ajax({ url: "messages.php", type: "POST", async: true, data: { WHAT GOES HERE ? }, dataType: "html", success: function(data) { $('#output').html(data); }, }); 

messages.php
我知道INSERT查询会在这里,但我无法想象如何从我的textarea的POST中获取值。

 <?php $host = "localhost"; $user = "root"; $pass = "root"; $databaseName = "myDataBaseName"; $tableName = "comments"; $con = mysql_connect($host,$user,$pass); $dbs = mysql_select_db($databaseName, $con); $result = mysql_query("SELECT * FROM $tableName ORDER BY date DESC LIMIT 0 , 10 "); $data = array(); while ($row = mysql_fetch_array($result)) { echo $row['message']." - ".$row['date']; echo "
"; } ?>

你可以发送该物业的任何东西。 试试这个:js

 $.ajax({ url: "messages.php", type: "POST", data: 'show=content', success: function(data) { $('#output').html(data); }, }); 

messages.php

 if(isset($_POST['show']) && $_POST['show']=='content') { // rest of your code goes here.. } 

还有一件事。 使用MySQLi代替MySQL,因为它现在已被弃用。

  data: {'messagecontent': $("#message-content").val()}, 

这是Doc所说的:

data 类型:PlainObject或String

与请求一起发送到服务器的普通对象或字符串。

以下是关于Plain Object的一些信息: http : //api.jquery.com/Types/#PlainObject

请参阅下一个使用示例:

 var formData = "name=ravi&age=31"; //Name value Pair 

要么

 var formData = {name:"ravi",age:"31"}; //Array $.ajax({ url : "messages.php", type: "POST", data : formData, success: function(data, textStatus, jqXHR) { //data - response from server }, error: function (jqXHR, textStatus, errorThrown) { }, }); 

您可以使用onclick,或使用jQuery .click函数作为按钮…

你会把它放在脚本标签中,通常放在你的脑袋里或文件里面

 $("#message-submit").click(function() { //in here we can do the ajax after validating the field isn't empty. if($("#message-content").val()!="") { $.ajax({ url: "messages.php", type: "POST", async: true, data: { message:$("#message-content").val() }, //your form data to post goes here as a json object dataType: "html", success: function(data) { $('#output').html(data); }, }); } else { //notify the user they need to enter data } }); 

对于messages.php,现在可以在变量$ _POST [‘message’]中为您的PHP提供AJAX POST的值

 $sql = "INSERT INTO tableName (messages) VALUES ('".$_POST['messages']."')"; 

我能够使用链接而不是输入类型文本框和按钮进行上述代码:

  

在我的链接上:

 Florida