The AJAX connection form does not work

advertisements

I have the following ajax script and form to login to my website:

<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>

 <legend>Log In</legend>
<div class="input-group">
  <span class="input-group-addon">E-Mail</span>

  <input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
  <span class="input-group-addon">Password</span>

  <input type="password" class="form-control" name="password" />
  </div>

</fieldset>

<input type="submit"  class="btn btn-primary" value="Log In" name="submit" />

</form></div>
<script>
$.ajax({
    type: "post",
    url: "/doLogin",
    data: $('#login').serialize(),
    success: function(result) {
                if(result == " success"){
                    window.location = "/index.php";
                }else if(result == " failure"){
                    $("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
                    //$("#alert").show();
                }
    }
});

but it doesn't preform the ajax, and brings me to the result page, which is not what I want. Is there any specific reason that the AJAX is not working? I'm kind of new to JavaScript so sorry if this is obvious.


You are running the Ajax function as soon as the script loads, and not doing anything to prevent the form from submitting normally when the form submits.

You need to move the JS you have already into a function. Then bind that function as a submit handler on the form. Then prevent the default behaviour of the submit event.

$('#login').on("submit", function(event) {
  event.preventDefault();

  $.ajax({
    type: "post",
    url: this.action,
    data: $(this).serialize(),
    success: function(result) {
      if (result == " success") {
        window.location = "/index.php";
      } else if (result == " failure") {
        $("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
        //$("#alert").show();
      }
    }
  });

});
<form action="/doLogin" method="post" id='#login'>

  <fieldset>
    <legend>Log In</legend>
    <div class="input-group">
      <label for="email" class="input-group-addon">E-Mail</label>

      <input type="email" class="form-control" name="email" id="email" value="" />
      <br />
    </div>
    <div class="input-group">
      <label class="input-group-addon" for="password">Password</label>

      <input type="password" class="form-control" name="password" id="password" />
    </div>

  </fieldset>

  <input type="submit" class="btn btn-primary" value="Log In" name="submit" />

</form>
</div>

That said - when you successfully login, you just redirect to another page. You are almost certainly better off not using Ajax at all for this.