Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Why does ajax request execute before code in beforeSend finishes executing?

This is my code. Basically I have a Reload.gif that I want to start playing on my page before I send an ajax request to reload my data. However what ends up happening is it will only start playing after my success function is called. This is what the timeline looks like:

0:00 seconds: 1 logged to console

0:00 seconds: 2 logged to console

0:10 seconds: 3 logged to console

0:10 seconds: GIF starts playing.

This doesn't make sense, is setting the src of an img async or something? Image code:

<img id="reloadIcon" src="/img/Reload.png" style="width: 25px; height: 25px"/>

jQuery.ajax({
    url: url,
    type: 'GET',
    timeout: 20000,
    beforeSend: function() {
        console.log(1);
        document.getElementById('reloadIcon').src = "/img/Reload.gif";
        console.log(2);
    },
    success: function (result) {
        console.log(3);
    }
});
like image 545
loopthedoop Avatar asked Jul 17 '26 06:07

loopthedoop


1 Answers

Load the image before $.ajax() call. Toggle the CSS display property of the <img> element at beforeSend function, instead of changing the .src of the <img> element.

jQuery.ajax({
    url: url,
    type: 'GET',
    timeout: 20000,
    beforeSend: function() {
        console.log(1);
        document.getElementById('reloadIcon').style.display = "block";
        console.log(2);
    },
    success: function (result) {
        document.getElementById('reloadIcon').style.display = "none";
        console.log(3);
    }
    , error: function() {
        document.getElementById('reloadIcon').style.display = "none";
    }
});
like image 143
guest271314 Avatar answered Jul 18 '26 20:07

guest271314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!