Reputation:
I am trying to create a commenting system for my site. A script is used to show massages (or alert) when the comment is submitted. I don't have enough knowledge in js to debug and fix this problem myself so I though I would ask here till I learn more about js.
My script imports which are in the header:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" async></script>
<script type="text/javascript" src="/js/main.js" async></script>
And my main.js script:
// Static comments
jQuery(document).ready(function ($) {
var $comments = $('.js-comments');
$('#comment-form').submit(function () {
var form = this;
$(form).addClass('submitting');
$('#comment-form-submit').html('Loading ...');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
$('#comment-form-submit').html('Submitted');
$('.new-comment-form .js-notice').removeClass('notice--danger').addClass('notice--success');
showAlert('<p style="color:#47bd40">Thanks for your comment! It will show on the site once it has been approved.</p>');
},
error: function (err) {
console.log(err);
$('#comment-form-submit').html('Submit Comment');
$('.new-comment-form .js-notice').removeClass('notice--success').addClass('notice--danger');
showAlert('<p style="color:#e64848">Submission failed, please fill in all the required inputs.</p>');
$(form).removeClass('submitting');
}
});
return false;
});
function showAlert(message) {
$('.new-comment-form .js-notice').removeClass('hidden');
$('.new-comment-form .js-notice-text').html(message);
}
});
My problem is, if I submit the comment, the script doesn't work, but if I waited for sometime and submitted again, it works just fine.
I am guessing it has something to do with loading the scripts and running them, I saw some similar questions here but non of the answers fixed my problem.
Upvotes: 0
Views: 1767
Reputation: 111
Async on your script tags means 'Asynchronous'.
Usually, when you load a webpage, the browser will request (if not in its updated cache already) all the files and imports that are specified in your main html. One of these things that are loaded at start up is all your script tags.
But you have async in there.
So your code is not running because it doesn't exist yet!
Remove async and it should run fine.
Upvotes: 1