I wanna convert this snippet from Jquery Ajax to Fetch Pure Javascript. Can help me please?
I tried this before, but my code doesn't work as it should. I even asked the question here.
That's why I would like you to help me to convert it from zero, I could not.
ajaxCall = $.ajax({
url: "data.php",
dataType: "json",
cache: false,
type: "POST",
data: "ajax=1&do=check&lista=" encodeURIComponent(leray[chenille]),
success: function (oreen) {
switch (oreen.enviando) {
case -1:
chenille ;
$("#div1").append(oreen.cat "<br />");
updateProgress(chenille, leray.length);
tvmit_wrongUp();
break;
case 1:
chenille ;
$("#div1").append(oreen.dog "<br />");
updateProgress(chenille, leray.length);
tvmit_wrongUp();
break;
case 2:
chenille ;
$("#div2").append(oreen.sky "<br />");
nieva ;
updateProgress(chenille, leray.length);
tvmit_dieUp();
break;
case 3:
chenille ;
$("#div3").append(oreen.water "<br />");
tvmit_liveUp();
updateProgress(chenille, leray.length);
break;
}
OKTY(leray, chenille, aarsh, nieva);
}
});
return true;
CodePudding user response:
You can go with this.
- URL is first option in the
fetch
method. cache: false
equivalent in fetch iscache: 'no-cache'
type: POST
equivalent in fetch ismethod: 'POST'
- You can add
data
as query in the URL - To convert data to
JSON
after getting theresponse
, then executereponse.json()
Lastly, you need to execute this in an async
function, so you can await
, or instead use then
syntax.
try {
const response = await fetch(`data.php?ajax=1&do=check&lista=${encodeURIComponent(leray[chenille])}`, {
method: 'POST',
cache: 'no-cache'
})
const oreen = response.json();
switch (oreen.enviando) {
case -1:
chenille ;
$("#div1").append(oreen.cat "<br />");
updateProgress(chenille, leray.length);
tvmit_wrongUp();
break;
case 1:
chenille ;
$("#div1").append(oreen.dog "<br />");
updateProgress(chenille, leray.length);
tvmit_wrongUp();
break;
case 2:
chenille ;
$("#div2").append(oreen.sky "<br />");
nieva ;
updateProgress(chenille, leray.length);
tvmit_dieUp();
break;
case 3:
chenille ;
$("#div3").append(oreen.water "<br />");
tvmit_liveUp();
updateProgress(chenille, leray.length);
break;
}
OKTY(leray, chenille, aarsh, nieva);
}
} catch (e) {
console.log(e)
}