-1

I have js code :

$('#button').on('click', function(e){
    console.log('start');

    if(xhr != ''){
        console.log('terminate');
        xhr.abort()
    }else{
        console.log('NOT terminate');
    }

    xhr = $.ajax({
        url: url,
        method: method,
        success: function(json) {
            console.log(json);
        },
    });
    console.log('end');
    return false;
});

and server laravel code:

public function update(Request $request)
{
    DB::transaction(function () {
       sleep(10);
       Product::find(1)->increment('user_id');
    });
    return 'test';
}

when I double click button output is :

start
NOT terminate
end
start
terminate
end
test

user_id is initially 1, but after execution it is 3 but I want to be 2. So how to terminate(abort) laravel execution from javascript ?

fico7489
  • 7,931
  • 7
  • 55
  • 89
  • 2 clicks = 2 times called event = 2 times executed your ajax, so 2 times incremented = 1+1+1 = 3, change the event instead of click use `dblclick` event. – Troyer Mar 01 '17 at 08:35
  • @Troyer I am looking for mechanism to terminate php exection from javascript, this above is just plain example where is not explained why I need this.... – fico7489 Mar 01 '17 at 08:38
  • There is no way to stop PHP server side execution from JS, you could add more parameters in your ajax to create the conditions on the ajax function controller :) – Troyer Mar 01 '17 at 08:40
  • Maybe create global variable in js named 'counter' and after first click increment it. Than check `counter == 1 ? setTimeout(() => {}, 3000) : ` – Grynets Mar 01 '17 at 08:40

2 Answers2

1

You cannot terminate php execution from inside javascript, they are asyncronous. Each ajax request start a server side php processing that, usually, return a response. But javascript has no control over the server side php once he has sent the request.

dparoli
  • 8,891
  • 1
  • 30
  • 38
0

If you want to abort current AJAX petition you have to declare xhr variable as global.

How to cancel/abort jQuery AJAX request?

But if you want to execute 1 AJAX petition on a double click, why don't try to use dblclick event?

https://api.jquery.com/dblclick/

Community
  • 1
  • 1
Gerard
  • 66
  • 6