I have looked at this post: Inserting into MySQL from PHP (jQuery/AJAX) but I didn't get the code to work. It's a quite old post so it might not work anymore?
I want to insert a post from my website (PHP) into my database (MySQL) without updating the page. I'm looking at AJAX (for example the link above) but I don't understand how to get it to work.
I have also looked at this video: https://www.youtube.com/watch?v=lwo4fAqaVFM for loading data and that's very simple so I thought it would be as simple to insert, but it wasn't...
Can anyone help me?
This new save.php actually works.
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form id="example" method="post">
<input name="textbox">
<input type="button" name="submitbuttonname" value="submit" onClick="$.post('save.php', $('form#example').serialize())">
</form>
</body>
New save.php
$db = new mysqli('localhost','root','','audf');
mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');
if($db->connect_errno){
die('Sorry, we are having some problems.');
}
$firstName = $_POST["firstName"];
$db->query("INSERT INTO test_db (first_name) VALUES ('".$firstName."')");
Old save.php
$db = new mysqli('localhost','root','','audf');
mysqli_set_charset($db, 'utf8') or die('Charset kunde inte ändras till UTF-8');
if($db->connect_errno){
die('Sorry, we are having some problems.');
}
if($_POST["submitbuttonname"]) {
$q = $db->prepare("INSERT INTO test_db (first_name) VALUES (?)");
$q->execute(array($_POST["textbox"]));
}