This is my first time using AJAX. I'm Trying to write data from an HTML form to a phpmyadmin database. I'm using jQuery for the AJAX call. I suspect there's something wrong in the jQuery because I've included a Javascript alert
with echo
at the top of the registerUser.php
file and it won't appear when I attempt to run this code, so the PHP is not even running. No Javascript errors in the browser. I appreciate your insight.
function registerUserViaAjax() {
$.ajax({
type: "POST",
url: "registerUser.php",
data: {
registerUsername: $('#registerUsername').val(),
registerPassword: $('#registerPassword').val(),
registerPassword: $('#registerEmail').val()
}
})
}
<label>Username</label>
<input class="w3-input" type="text" id="registerUsername">
<label>Password</label>
<input class="w3-input" type="password" id="registerPassword">
<label>Confirm Password</label>
<input class="w3-input" type="password" id="registerConfirmPassword">
<label>Email Address</label>
<input class="w3-input" type="text" id="registerEmail">
<button class="w3-btn w3-green" style="margin-top:3%;margin-bottom:3%" id="registerButton" onclick="registerUserViaAjax()">Go</button>
<?php
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'fall2167';
$dbc = mysqli_connect($host, $user, $pw, $db)
or die('LOCAL CONNECT ERROR: '. mysqli_connect_error());
$uname = mysqli_real_escape_string($dbc, $_POST['registerUsername']);
$pword = mysqli_real_escape_string($dbc, $_POST['registerPassword']);
$pword = password_hash($pword, PASSWORD_DEFAULT);
$email = mysqli_real_escape_string($dbc, $_POST['registerEmail']);
$check = mysqli_query($dbc, "select id from hw6 where uname = '$uname'")
or die('confirm6 read error: ' . mysqli_error($dbc));
if (mysqli_num_rows($check) != 0)
{
echo "<script> usernameTaken(); </script>";
exit;
}
$query = "insert into users(uname, pword, email)" . "values('$uname','$pword','$email')";
$result = mysqli_query($dbc, $query)
or die('DB Write Error: ' . mysqli_error($dbc));
echo "<script> openSuccessMessage(); </script>";
mysqli_close($dbc);
?>
You should use done
and fail
callbacks to make sure what happen and what is the response you're getting back from the server side :
$.ajax({
type: "POST",
url: "registerUser.php",
data: {registerUsername: $('#registerUsername').val(), registerPassword: $('#registerPassword').val(), registerPassword: $('#registerEmail').val() },
})
.done(function(response) {
alert( response );
//call you function 'openSuccessMessage' here
openSuccessMessage();
})
.fail(function(response) {
alert( response );
});
Your openSuccessMessage
should be called in the callback and not inside the PHP code.
NOTE : Add try{ }catch(){}
in your PHP code to debug the instructions and show the response in alert as shown in the above code.
Hope this helps.