Home > OS >  Convert AJAX Jquery to Vanilla Javascript (POST) with .fetch async
Convert AJAX Jquery to Vanilla Javascript (POST) with .fetch async

Time:09-10

I am trying to change this .ajax call from Jquery to pure Javascript.

And this way I receive the JSON in my PHP: echo '{"enviando":-1,"example":"<span class=text-primary><strong>' . $exampleresult . '</strong></span>"}';

JQUERY CALL:

ajaxCall = $.ajax({
    url: "data.php",
    dataType: "json",
    cache: false,
    type: "POST",
    beforeSend: function (si) {
        $("#div").html("<img src=''/>");
    },
    data: "ajax=1&do=check&lista="   encodeURIComponent(leray[chenille]),
    success: function (oreen) {
        switch (oreen.enviando) {
            case -1:
                //código
                break;

            case 1:
                //código
                break;

            case 2:
                //código
                break;

            case 3:
                //código
                break;

            case 0:
                //código
                break;
        }

        GRAX(leray, chenille, aarsh, nieva);
    }
});
return true;

And this is my try with Vanilla Javascript:

But I get the error: SyntaxError: Unexpected end of JSON input at envSoli. And the error line: let resultado = await peticion.json();

What is the problem? How can I fix it? I'm just learning about JavaScript requests.

const envSoli = async () => {
  try {
    let peticion = await fetch("data.php", {
      method: "POST",
      body: JSON.stringify({
        data: "ajax=1&do=check&lista="   encodeURIComponent(leray[chenille])
      }),
      headers: { "Content-type": "application/json" }
    });
    let resultado = await peticion.json();
    const holap = (oreen) => {
      switch (oreen.enviando) {
        case -1:
          break;

        case 1:
          break;

        case 2:
          break;

        case 3:
          break;

        case 0:
          break;
      }

      OKTY(leray, chenille, aarsh, nieva);
    }
    console.log(resultado);
    return true;
  } catch (error) {
    console.log(error)
  }
}
envSoli();

CodePudding user response:

This is a little more old-school, but it may help uncover what the error is. Try making the call like this:

function check() {

    var request = new XMLHttpRequest();
    var url = "data.php";
    var params = JSON.stringify({
        data: "ajax=1&do=check&lista="   encodeURIComponent(leray[chenille])
    });

    request.open('POST', url, true);

    request.setRequestHeader('Content-Type', 'application/json');

    request.onreadystatechange = function() {

    if (request.readyState == 4 && request.status = 200) {
    
        // handle response here...
    }

}

Credit to these sources during my search:

jquery ajax to vanilla javascript (normal javascript) code conversion request

Send POST data using XMLHttpRequest

Hope this helps!

CodePudding user response:

You shouldn't call JSON.stringify(), since the original jQuery code didn't send JSON. The body: parameter should be the same as the data: parameter in $.ajax.

body: "ajax=1&do=check&lista="   encodeURIComponent(leray[chenille])
  • Related