When a user clicks the button we should check they are logged in via an ajax request. Only after the ajax request has returned should my form show.
The ajax request returns an error (intentionaly for illustration purposes) yet my form still shows.
How can I modify my code so the display_form() will only run after check_loggedin() has completed?
Thank you very much.
PS I am aware there are various posts about promises but despite trying I have not managed to understand them - it would be really helpful if someone could please modify my code so I understand where I'm going wrong - thank you.
$(document.body).on('click', "#check_logged_in_show_form_if_true", function(){
check_loggedin().then(display_form());
});
function check_loggedin(myurl) {
return $.ajax({
method: 'get',
url: 'https://www.this-domain-will-cause-ajax-request-to-error.com',
data: {
foo: 1,
},
traditional : true,
beforeSend: function() {
},
success: function(data){
console.log('logged in - ok to show form');
return true
},
error: function(data){
// not logged in prompt user to sign in
console.log('ajax failed - do not show form');
return false
}
});
};
function display_form() {
$('#myform').show();
};
<div class="alert alert-success" id="myform" style="display: none;">
Only show this form if ajax request is successful
<input type="text" name="input" placeholder="" value="" class="form-control" >
</div>
<hr />
<span class="btn btn-primary" id="check_logged_in_show_form_if_true" >Display form if ajax request is successful (form should not show)</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>