Cedirck
Cedirck

Reputation: 35

javascript ajax success function not woking?

I know this has many duplicates but somehow neither of those questions (I've search almost every same title in stack overflow) work. My problem here is that the success function does not not fire the alert message and I can't figure out why.

<form>
  <div class="form-group">
    <label for="">Username</label>
    <input type="text" class="form-control" id="user" name="user" placeholder="Username">
  </div>
  <div class="form-group">
    <label for="">Password</label>
    <input type="password" class="form-control" id="pass" name="pass" placeholder="Password">
  </div>
  <div class="form-group">
    <label class="radio-inline">
      <input type="radio" data-toggle="buttons-radio" name="optRadio" value="prof">Professor
    </label>
    <label class="radio-inline">
      <input type="radio" data-toggle="buttons-radio" name="optRadio" value="admin">Admin
    </label>
  </div>
  <button type="button" class="btn btn-block btn-social" onClick="validateForm()">
    <span class="fa fa-twitter"></span>Login
  </button>
</form>

The javascript file

function validateForm() {
  var checkUser = document.getElementById("user").value;
  var checkPass = document.getElementById("pass").value;
  var checkOption = $("input[name=optRadio]:checked").val();
  /*
    if (checkUser && checkPass && checkOption) { //checks if user is not empty
    } else {
        alert ("Please fill up all information");
    }
  */
  if (checkOption == "prof") {
    $.ajax({
      type: 'POST',
      url: 'assets/connection/login.php',
      dataType: 'json',
      data: {
        user: checkUser,
        pass: checkPass,
      },
      beforeSend: function() {
        alert("a")
      },
      success: function(response) {
        alert(response)
      }
    });
  }
}

and the php file only contains this

<?php echo "js test" ?>

EDIT: As pointed out in comments and by @Rax Weber's answer, there was a typographical mistake in sucess (should be success), but this is not the root cause of problem and still alert does not fires after correcting it.

Upvotes: 3

Views: 98

Answers (2)

Rax Weber
Rax Weber

Reputation: 3780

It should be success, not sucess.

sucess: function (response) {
  ^
    alert (response)
}

Edit: The question has been updated/edited. Previously, it had a semantics mistake as I have mentioned above.

Upvotes: 1

Yogesh Mistry
Yogesh Mistry

Reputation: 2152

The reason is that, you have set dataType: 'json', and not getting response in JSON. Possible solutions:

  1. Send the response in JSON. In you post file, send JSON encoded output: <?php echo json_encode("js test"); ?>

  2. Let the dataType be set to default. Remove the line dataType: 'json' from your JS.

Upvotes: 3

Related Questions