Using an AJAX call to submit form data to


Currently, my website has a login form which uses method="POST" to send the username and password to, which in turn accesses the login database, does some error handling, and either returns a ?login=success or ?login=error. The site also contains a contact form, which using JavaScript, sends an Ajax call to I would like to implement this same procedure for my login & signup forms as well. I have tried copying contact.js to login.js and made some modifications to fit the login form / but it is inoperable at this point in time. Here is some of the code to reference.

login form

        <!-- login form -->
        <form name="loginForm" id="loginForm">
          <div class="imgcontainer">
            <img class="avatar" id="blacksheep" src="img/blacksheep.png" alt="Avatar">
          <div class="container text-center">
            <input type="text" class="form-control" name="username" id="username" placeholder="Userame"
            required data-validation-required-message="Please enter your username.">

            <p class="help-block text-danger"></p>

            <input type="password" class="form-control" name="password" id="password" placeholder="Password"
            required data-validation-required-message="Please enter your password.">
            <p class="help-block text-danger"></p>
            <input type="checkbox" checked="checked"> Remember me

          <div class="container" style="background-color:#f1f1f1">
            <button type="button" class="redbtn" onclick="window.location.href='index.php'">Cancel</button>
            <button type="submit" class="bluebtn" name="loginButton" id="loginButton">Login</button>

            <span class="psw">Forgot <a href="#">password?</a></span>


$(function() {

  $("#loginForm input,#loginForm textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
      // additional error messages or events
    submitSuccess: function($form, event) {
      event.preventDefault(); // prevent default submit behaviour
      // get values from FORM
      var username = $("input#username").val();
      var password = $("input#password").val();
      var name = username; // For Success/Failure Message
      // Check for white space in name for Success/Fail message
      if (name.indexOf(' ') >= 0) {
        name = username.split(' ').slice(0, -1).join(' ');
      $this = $("#loginButton");
      $this.prop("disabled", true); // Disable login button until AJAX call is complete to prevent errors
        url: "../includes/",
        type: "POST",
        data: {
          username: username,
          password: password
        cache: false,

        error: function() {
          // Fail message
          $('#success').html("<div class='alert alert-danger'>");
          $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
          $('#success > .alert-danger').append($("<strong>").text("Sorry " + name + ", it seems that my login server is not responding. Please try again later!"));
          $('#success > .alert-danger').append('</div>');
          //clear all fields
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 1000);
    filter: function() {
      return $(this).is(":visible");

  $("a[data-toggle=\"tab\"]").click(function(e) {

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {



  // check whether the loginbtn was clicked
if (isset($_POST['loginbtn'])) {

  include_once '';

    // initialize variable
  $uid = trim($_POST['uid']);
  $pwd = trim($_POST['pwd']);

    // error handlers

    // check if inputs are empty
  if (empty($uid) || empty($pwd)) {

    $conn = null;
    header("Location: ../index.php?login=error_field");

  } else {

      // check if username is in database
    $stmt = $conn->prepare("SELECT user_uid FROM users WHERE user_uid = ?");

    if ($stmt->rowCount() < 1) {

      $conn = null;
      header("Location: ../index.php?login=error_username");

    } else {

        // check if password is correct
      $stmt = $conn->prepare("SELECT user_pwd FROM users WHERE user_uid = ?");
      $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // dehashing the password
      $hashedPwdCheck = password_verify($pwd, $result[0]['user_pwd']);

      if ($hashedPwdCheck == false) {

        $conn = null;
        header("Location: ../index.php?login=error_password");

      } else {

          // login the user in
        $stmt = $conn->prepare("SELECT user_id, user_first, user_last, user_email, user_uid FROM users WHERE user_uid = ?");
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $_SESSION['user_id'] = $result[0]['user_id'];
        $_SESSION['user_first'] = $result[0]['user_first'];
        $_SESSION['user_last'] = $result[0]['user_last'];
        $_SESSION['user_email'] = $result[0]['user_email'];
        $_SESSION['user_uid'] = $result[0]['user_uid'];

        $conn = null;
        header("Location: ../updates.php?login=success");




} else {

  header("Location: ../index.php?login=error");


?> is working correctly, and login.js calls qBootstrapValidation.js which I have pasted here due to its size. Ultimate goal? Use JavaScript & Ajax to POST form input to the script.


Some good advice here is to ignore the AJAX part of it for now and just focus on getting it working as form submits to PHP code.

Then once it is working, your code will be in a better spot to work using AJAX to help improve the user experience.


they do work at the moment without the javascript/ajax.


Good one. Separate the code that gets the post variables, from the rest of the code that does the checking. You can then pass those post variables as function parameters to the rest of the code.

That way the function can be moved out to a separate file, and included both by the file as well as by a new php file for the ajax login.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.