Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ZandA's avatar
Level 1

Ajax async with beforesend

I wanna call Ajax and wait til it finish to response data, and also before Ajax sends request, I wanna do some actions; but it does not seem to work, any solutions please?

0 likes
10 replies
ZandA's avatar
Level 1

@Sinnbeck here is my code:

$.ajax({
                            url: url,
                            type: 'delete',
                            data: {
                                _token: "{{csrf_token()}}"
                            },
                            async:false,
                            beforeSend:function(){
                                spinner.show();
                            },
                            success: function(response) {
                                spinner.hide();
                                notify(response.status, response.msg);
                                table.ajax.reload( null, false );
                            }
                        });

but spinner shows only after Ajax responds

Sinnbeck's avatar

@Saren Um Just do it on the line before the ajax?

spinner.show(); //here
$.ajax({
                            url: url,
                            type: 'delete',
                            data: {
                                _token: "{{csrf_token()}}"
                            },
                            async:false,
                            success: function(response) {
                                spinner.hide();
                                notify(response.status, response.msg);
                                table.ajax.reload( null, false );
                            }
                        });
ZandA's avatar
Level 1

@Sinnbeck I don't know why it's still not working, Ajax keeps executing first and spinner shows after

Sinnbeck's avatar

@Saren Um beforeSend() is for changing the request, so I dont know how it reacts if you run arbitrary code in it.

Maybe try returning true to ensure it is run

                            beforeSend:function(){
                                spinner.show();
                                return true;
                            },
ZandA's avatar
Level 1

@Sinnbeck Ajax always starts first. Now I put Ajax in setTimeout just to delay and it helps

Sinnbeck's avatar

@Saren Um Is that spinner.show(); slow? I assumed it just added something to the DOM, which should be so fast it would be done before the ajax has time to even start

Please or to participate in this conversation.