Defyleiti
Defyleiti

Reputation: 555

Ajax call a number of times

I need to call an ajax a number of times to write to a named pipe in linux.

Here's my code.

Javascript and ajax

var count = 0;
var status = "online";

while(status=="online" && count!=25){

$.ajax({ url: 'http://192.168.5.10/Command.php',
         data: {cmd: 'GORIGHT'},
         type: 'post',
         success: function(data) {
                      console.log(data);
                  }
});

count++;
}

Command.php

if($_POST['cmd']==="GORIGHT"){

$fd = fopen("/tmp/myFIFO","w");
fwrite($fd, "GORIGHT\n");
fclose($fd);
echo "SUCCESS";
}

Is this the right way of doing it?. Or is there a much faster way of doing it?.. Will this create a delay?

EDIT: Change the ajax url. sorry about that.

Upvotes: 0

Views: 126

Answers (1)

Frederik.L
Frederik.L

Reputation: 5620

If you need it to be synchronous, you will need to make sure that every calls are waiting completion of the previous one. Something like this should do the trick, untested thought:

var count=0;
var N=25;
loop();

function loop() {
    $.ajax({ url: 'http://192.168.5.10/Command.php',
        data: {cmd: 'GORIGHT'},
        type: 'post',
        success: function(data) {
            console.log(data);
        }
    })
    .done(function(data){
        if (count < N) {
            count++;
            loop();
        }
    });
}

Another idea (faster) could be to add an extra parameter in Command.php to allow you to specify how many time a predefined action must be done. You could have something like this instead:

var N=25;

$.ajax({ url: 'http://192.168.5.10/Command.php',
    data: {cmd: 'GORIGHT', repeat:N},
    type: 'post',
    success: function(data) {
        console.log(data);
    }
});

Upvotes: 1

Related Questions