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 t
you can use an onclick, or use a jQuery .click function for the button...
you would put this in script tags, usually in your head or inside the document.ready
$("#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
}
});
for messages.php, the value of your AJAX POST will now be available to your PHP in the variable $_POST['message']
$sql = "INSERT INTO tableName (messages) VALUES ('".$_POST['messages']."')";
EDIT/UPDATE: Six years later my original answer received another up vote so I feel it is probably relevant to post an update that the above is now globally accepted as being incredibly insecure. The jQuery used should be placed at the end of your document in the $(document).ready() method or preferably loaded in from a single minified app.js file. That aside, you will likely want to incorporate some form of CSRF (Cross Site Request Forgery) token system to help keep bots from slamming your form with spam and potentially malicious data, which leads to the next point.
The SQL listed here takes the raw data from the post data and places it in the insert statement. At the bare minimum you should be sanitizing that data. If you are using mysqli you can use the mysqli::real_escape_string($str) static method (http://php.net/manual/en/mysqli.real-escape-string.php) to sanitize any user provided data being placed in the query.
However, a much better method now would be to use prepared statements with PDO so that the data provided gets bound to query in such a way that it can only be used as intended. http://php.net/manual/en/pdo.prepare.php