Increasing range until get results

I have a functionality that submits some parameters via AJAX and displays returned results.

setTimeout(function(){
    var request = new XMLHttpRequest();
    request.open("POST", "/ajax.php", true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {

            document.getElementById("lst").innerHTML = this.response;
            
    };

    request.send("op=list&lt="+lat+"&ln="+lon+"&mi=1");

}, 1500);

It works but sometimes no results are found and I need to increase the last parameter "mi" to a higher value and repeat the submission. I decided to create an array and loop through it until I get results.

setTimeout(function(){
    var dist= new Array(1,5,10,20,50);

    dist.every(v => {
        var request = new XMLHttpRequest();
        request.open("POST", "/ajax.php", true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        request.onload = function () {
            if (this.status >= 200 && this.status < 400) {    
                document . getElementById("lst") . innerHTML = this . response;
                return false;
            };

            request . send("op=list&lt=" + lat + "&ln=" + lon + "&mi="+v);
            return true;
        }
    });

}, 1500);

That’s theory, not sure how to put it all together.

1 thought on “Increasing range until get results”

  1. Don’t use setTimeout or setInterval — those will wait an arbitrary amount of time, which will either be too short (leading to bugs) or too long (leading to poor performance). Instead, wait for each request to finish before starting the next one.

    This can be achieved fairly easily with the fetch API and async/await:

    const DISTANCES = [1, 5, 10, 20, 50]
    
    ;(async () => {
        const url = new URL('/ajax.php', window.location.origin)
    
        for (const distance of DISTANCES) {
            const res = await fetch(url, {
                method: 'POST',
                headers: [
                    [
                        "Content-Type",
                        "application/x-www-form-urlencoded; charset=UTF-8",
                    ],
                ],
                body: `op=list&lt=${lat}&ln=${lon}&mi=${distance}`,
            })
    
            if (res.ok) {
                document.getElementById("lst").innerHTML = await res.text()
    
                break
            }
        }
    })()
    
    Reply

Leave a Comment