php - How can I be sure of jquery ajax call is executing for each visitor? ← (PHP, JavaScript, JQuery)

I have a php counter "counter.php" called from a javascript file. I want to be sure, for each and every visitor this counter.php is called when the dom finsihes loading. I wrote this piece of code :

$(document).ready(function (){
$.ajax({
    url:"https://www.cloudflare.com/cdn-cgi/trace",
    cache:false,
    timeout:5000,
    success:function(data){
        cc=data.match(/loc=(.*)\n/);
        $.get('counter.php?cc='+cc[1]);
    },
    error:function(){
        $.get('counter.php');
    }
});
});

I have jquery embedded. Is this enough to be sure the counter.php file is called for each and every visit? I mean is the ajax call executed for each visit? Is there any possibility that either success: or error: functions of ajax call cannot be executed?

Answer



Solution:

You can update another counter in a complete callback to verify each user has triggered the call. Match the complete counter with unique visit counters and you can be sure this is being fired, whether error or success.

https://api.jquery.com/ajaxcomplete/

Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.

Source