0

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"]));
}
Community
  • 1
  • 1

3 Answers3

1

Your form is sending the data as $_GET;
Add method="POST" to your <form> element.

edit: Oh. OK I didn't fully read your code:

Your form is probably being sent before it fires the $.post request.
Try changing the input type from "submit" to "button".

Regards ;)

Ezenhis
  • 997
  • 9
  • 14
  • Thanks for your help but it still doesn't work. It won't put anything into the database. Anything in save.php that looks wrong? – PoorCadaver Apr 12 '16 at 09:04
  • You could try to display `$db->errno` after preparing the INSERT – Ezenhis Apr 12 '16 at 09:16
  • It doesn't show anything... It's like save.php doesn't even load. – PoorCadaver Apr 12 '16 at 09:24
  • Try to open the Inspector console (right click anywhere on the page and select "Inspect" - should be similar in both FF and Chrome) and go to the Network tab. You should see a new entry each time you click on the $.post requesting button. – Ezenhis Apr 12 '16 at 09:33
  • or you could add a third parameter to the $.post function and have it look like: `$.post('save.php', $('form#example').serialize(), function(res){alert(res)} )` This way you should have an alert with the output of save.php – Ezenhis Apr 12 '16 at 09:36
  • The network inspector showed that save.php was loaded with the POST protocol. The function returns an alert that says: Undefined index: submitbuttonname in .../save.php on line 9. – PoorCadaver Apr 12 '16 at 09:39
  • Updated the original post again. The new save.php actually works now. Do you think my changes are legit? :) – PoorCadaver Apr 12 '16 at 09:57
  • Glad you made it working. Prepared statements are considered a better practice (they're safer against SQL injections) but whatever works, works. – Ezenhis Apr 12 '16 at 10:06
1

For a cleaner code, I made some modifications.

html

<form id="example" method="post">
    <input name="textbox">
    <input type="button" name="submitbuttonname" value="submit">
</form>

ajax using POST method to call save.php

$('#example').submit(function(e){
e.preventDefault();

var frmdata = $('#example').serializeArray();

$.ajax({
    url: 'save.php',
    type: 'POST',
    data : frmdata,
    dataType: 'json',
    success: function(data){
        alert("Saved!");
    },
    error: function(err) {
        console.log(err.responseText);
    }
});
});

save.php - binding parameters lacking

if($_POST["textbox"]) {
$textb = $_POST['textbox'];
$q = $db->prepare("INSERT INTO test_db (first_name) VALUES (?)");
$q->bind_param("s",$fname);
$fname = $textb;
$q->execute();

if($q){
 $array = array('data'=> $textb);
  echo json_encode($array);
}
}
graceth
  • 178
  • 8
0

The link is working until now. Something might not be working with your code. You could post a snippet of what you have tried so that we could find out what is missing. Happy Coding!

graceth
  • 178
  • 8