Pixeldoris Pixeldoris - 7 months ago 13
Javascript Question

ajax to submit php form to database, ajax part doesn't work

I'm very new to ajax so I followed a tutorial but I can't get it to work. I tried search this forum for an answer but with no luck..

HTML (a bit stripped down from classes and bootstrap-stuff)

<form id="editUserForm" role="form">
<input id="edit_employeenr" type="text" name="employeenr">
<input id="edit_name" type="text" name="name">
<select id="edit_membertype" name="membertype">
<option value="1">Admin</option>
<option value="2">Employee</option>
</select>
<input type="submit" value="Save">
</form>
<div id="editUserMsg">Successfully updated!</div>


JS

$(document).ready(function() {
$("#editUserMsg").hide();

$("#editUserForm").submit(function(event) {
event.preventDefault();
submitUserEdit();
});

function submitUserEdit(){
var dataString = $("#editUserForm").serialize();

$.ajax({
type: "POST",
url: "user_edit_process.php",
data: dataString,
success: function(text){
if (text == "success"){
userEditSuccess();
}
}
});
}

function userEditSuccess(){
$("#editUserMsg").show().delay(5000).fadeOut();
}
});


PHP (user_edit_process.php)

<?php
$employeenr = $_POST['employeenr'];
$name = $_POST['name'];
$membertype = $_POST['membertype'];

$stmt = $link->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?");
$stmt->bind_param("isi", $employeenr, $name, $membertype);
$stmt->execute();

if ($stmt) {
echo 'success';
} else {
echo 'fail';
}
?>


if i put the
$("#editUserMsg").show().dealy(5000).fadeOut();
just above the
$.ajax
the message appears, so that must mean that the ajax code isn't working correct. Any suggestions?

EDIT Solved. I had forgotten to include the file where the variable
$link
wes defined.

Answer

It seems that you have a problem in your either in your prepare statement or in the bind_parameter. You should always check for error, so I suggest you do like this to check for errors:

<?php
    $employeenr = $_POST['employeenr'];
    $name = $_POST['name'];
    $membertype = $_POST['membertype'];

    if (!($stmt = $mysqli->prepare("UPDATE users SET employeenr = ?, name = ?, membertype = ?"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }

    if (! $stmt->bind_param("isi", $employeenr, $name, $membertype)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
?>

and then in you JS, add this to your success method:

console.log(text);

Check your Firefox console (Ctrl-Shift-Q), and if there is an error you would find it under "Network" -> Click the "user_edit_process.php" in the list -> and in the right window under "Preview".