Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

send data to MySQL with AJAX + jQuery + PHP

I've been looking all day to find a way to insert some data into my database and then show the new data in the list of already existent data on my webpage.

I know that some of the points I can't get done may be basics but I just started learning Javascript/ AJAX so I have a limited knowledge.

I think that 70% of the job is done, I can display the data on my webpage using AJAX/jQuery/PHP but I can't figure how to send data from a "textarea" to my database using again AJAX/jQuery/PHP.

So far this is what I've done :

index.php
In this page, I figure that I need to put an onClick: function() on the button but I don't know where to put that function and what it should exactly do.

<!DOCTYPE html>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>TP2</title>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>

 <script src="javascript.js"></script>




    Message: <input type="text" id="message-content">
    <input type="button" id="message-submit" value="Envoyer">


    <div id="output" align="center">    
    </div>    

</body>  
</html>

javascript.js
This page contain the AJAX code that display my data in the #output div. I just don't know what to put in "data: {}" so the content of my textarea is sent to my php file.

$.ajax({
    url: "messages.php",
    type: "POST",
    async: true, 
    data: { WHAT GOES HERE ? },
    dataType: "html",

    success: function(data) {
        $('#output').html(data);    
    },  
});

messages.php
I know that the INSERT query will go here but I can't figure how to get the value from the POST of my textarea.

<?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 "<br />";
}

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 data: {'messagecontent': $("#message-content").val()},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...