Svinjica Svinjica - 5 months ago 7
jQuery Question

Problems with AJAX error event

I'm having problems with AJAX error event. I've manage to put together some code using questions/answers from this site (I'm javascript newb)

After successfully implementing success message on successful login and showing div element success (shown below)

<div class="alert alert-success"> <strong>Logging in..</strong></div>


I'm trying to show error message on unsuccessful login on my login modal form.
Here is the code for modal form

<form id="myform" method="POST" role="form">
<div class="modal fade" id="test" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title">Prijava</h4>
</div>
<div class="modal-body">
<div id="error">
<div class="alert alert-danger"> <strong>Error, try again!</strong> </div>
</div>
<div id="thanks">
<div class="alert alert-success"> <strong>Logging in..</strong></div>
</div>

<div class="form-group">
<label for="user">User:</label>
<input name="user" type="text" class="form-control" placeholder="Unesi korisnika">
</div>
<div class="form-group">
<label for="pass">Password:</label>
<input name="pass" type="password" class="form-control" placeholder="Unesi lozinku">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="reset" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" id="submitForm">Login in!</button>
</form>
</div>
</div>


And here is my code for AJAX code

$("#error").hide();
$("#thanks").hide();
$("#myform").submit(function (e) {
var url = "login.php";
$.ajax({
type: "POST",
url: url,
data: $('#myform').serialize(),
success: function (data) {
$("#thanks").show();
setTimeout(function() {
top.location.href ='admin.php';
}, 2000);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#error").show();
}
});
e.preventDefault();
});


Success event is working fine, but the problem lies in error event. No matter what I write, it shows
#thanks
div and completely ignores
#error
div. I just want to show #thanks on successfully login and #error div on unsuccessful login in modal form.

Answer

You need to send data back to the browser from the php on the server with a message for the ajax success function to process:

login.php

//do your stuff then
if (everything_is_OK) {echo "good to go!";} else {echo "problem";}

AJAX

success: function (data) {
           if (data==="good to go!"){$("#thanks").show();}
           if (data==="problem"){$("#error").show();}
           }
Comments