0
Good morning. I need to do several POST using Jquery, but they need to be sent one by one, paused.
Example: All survey data would be sent, then all environment data and so on.
Problem
As the server has character limitation in the POST, I can not send everything at once, it has to be sent in a paused form, and so you do not risk losing any record.
Problem of my created solution
This data is sent via cell phone, and for some reason sometimes does not send all the data.
My JS code
I tried to create a function sleep
:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//ENVIO N1
tx.executeSql('SELECT * FROM vistorias WHERE codigo=?', [codigo], async function (tx, rsVistoria) {
let rowsVistoria = rsVistoria.rows;
for (var i = 0; i < rowsVistoria.length; i++) {
$.post("https://url.com.br/arquivo.php", {
acesso:'vistorias',
codigo: rowsVistoria[i].codigo,
fotoFachada: rowsVistoria[i].fotoFachada
});
await sleep(1000);
}
})
//ENVIO N2
tx.executeSql('SELECT * FROM vistorias_OUTRA WHERE codigo=?', [codigo], async function (tx, rsVistoria) {
let rowsVistoria = rsVistoria.rows;
for (var i = 0; i < rowsVistoria.length; i++) {
$.post("https://url.com.br/arquivo.php", {
acesso:'vistorias',
codigo: rowsVistoria[i].codigo,
fotoFachada: rowsVistoria[i].fotoFachada
});
await sleep(1000);
}
})
My intention with the code above
Make each FOR
wait 1 second, to send the other record. After the end of the ENVIO N1
, passes to the ENVIO N2
, and so on.
Someone would have a better suggestion?
No Jquery manjo, do not know what the return of the post, if it is a
Promise
you can giveawait
in it, if the return is another, you can encapsulate in aPromise
, define howasync
and then give aawait
– Denis Rudnei de Souza
Take a look at this documentation: https://api.jquery.com/jQuery.getJSON/
– Alessandro
Wouldn’t it be better to give up Sleep and use the method
$.ajax
with the option ofasync: false
?– Benilson
@Benilson how I do it?
– Tiago
@Benilson could post an example?
– Tiago
Please take a look at the accepted answer on this link https://answall.com/questions/6392/awaitr-retorno-de-ajax-em-fun%C3%A7%C3%A3o-s%C3%Adncrona
– Benilson
@Benilson I put each Insert in one
function foo () {
different?– Tiago
I’ll put it in answer, so you understand better
– Benilson
@Benilson Thanks.
– Tiago
where $.post... you exchange for $.ajax... and stop using Sleep.
– Benilson