Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...