Home > OS >  How to convert this Jquery Ajax to Pure Javascript Fetch?
How to convert this Jquery Ajax to Pure Javascript Fetch?

Time:09-12

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.

  1. URL is first option in the fetch method.
  2. cache: false equivalent in fetch is cache: 'no-cache'
  3. type: POST equivalent in fetch is method: 'POST'
  4. You can add data as query in the URL
  5. To convert data to JSON after getting the response, then execute reponse.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)
    }
  • Related