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 />";
}
?>
data: {'messagecontent': $("#message-content").val()},
You can send anything in that property. Try this: 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..
}
One more thing. Use MySQLi instead of MySQL as it's a deprecated extension now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With