Svinjica Svinjica - 1 year ago 41
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 class="modal-body">
<div id="error">
<div class="alert alert-danger"> <strong>Error, try again!</strong> </div>
<div id="thanks">
<div class="alert alert-success"> <strong>Logging in..</strong></div>

<div class="form-group">
<label for="user">User:</label>
<input name="user" type="text" class="form-control" placeholder="Unesi korisnika">
<div class="form-group">
<label for="pass">Password:</label>
<input name="pass" type="password" class="form-control" placeholder="Unesi lozinku">
<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>

And here is my code for AJAX code

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

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

Answer Source

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:


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


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