Alexander Edwards Alexander Edwards - 1 year ago 84
jQuery Question

AJAX Post via jQuery and PHP

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

at the top of the
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() {
type: "POST",
url: "registerUser.php",
data: {
registerUsername: $('#registerUsername').val(),
registerPassword: $('#registerPassword').val(),
registerPassword: $('#registerEmail').val()

<input class="w3-input" type="text" id="registerUsername">

<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>

$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>";

$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>";

Answer Source

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 :

  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
  .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download