4lackof 4lackof - 3 months ago 11
HTML Question

jQuery - AJAX error: does not re-enable submit button

I have been working to get code which stops the user from sending multiple AJAX requests.

.one()
does not work for me. I have decided to use
.prop('disabled');
on my "submit" button to stop it from being able to send any more AJAX requests.

The theory for the flow-line was: user clicks submit button. send AJAX. disable submit. AJAX finishes. re-enable submit button.

I tried to put that to the test, but seems to not be working. Here's a snippet of my code (same as the jsfiddle I just linked):



//runs on $(document).ready();
console.log($('#submit').prop('disabled'));

$(document).on('click', '#submit', function(e) {
$.ajax({
type: 'GET',
url: '/FakeURL',
})
.done(function(data, textStatus, jqXHR) {
$('#gimme-data').append(data, textStatus, jqXHR);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$('#gimme-data').append(jqXHR, textStatus, errorThrown);
})
.always(function(data_jqXHR, textStatus, jqXHR_errorThrown) {
$('#gimme-data').append(data_jqXHR, textStatus, jqXHR_errorThrown);
$('#submit').prop('disabled', 'false');
console.log($('#submit').prop('disabled'));
});
});
$(document).ajaxStart(function() {
$('#submit').prop('disabled', 'true');
console.log($('#submit').prop('disabled'));
}).ajaxStop(function() {
$('#submit').prop('disabled', 'false');
console.log($('#submit').prop('disabled'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="submit" id="submit" class="first" value="GO!" title="Log In">
<div id="gimme-data">

</div>





As you can see when you run it,
$('#submit').prop('disabled')
always stays true (except, at the beginning, before anything happens).

This is after
$('#submit').prop('disabled', 'false');
gets set on both
.ajaxStop();
AND
.always()
;


Does anyone know why this happens and how to fix it?

Answer

You should pass a boolean value to the prop method as disabled is a boolean property. The 'false' is non-empty string which is coerced into the true boolean value. Use false instead.

Comments