0

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,"cat":"<span class=text-primary><strong>' . $exampleresult . '</strong></span>"}';

JQUERY CALL:

ajaxCall = $.ajax({
  url: "data.php",
  dataType: "json",
  cache: false,
  type: "POST",
  beforeSend: function (nautia) {
    //IMG NOT RELEVANT
    $("#checkStatus").html("<img src=''/>");
  },
  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;

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: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
        headers: { "Content-type": "application/x-www-form-urlencoded" }
      });
      let resultado = await peticion.json();
      function ola (oreen) {
        switch (oreen.enviando) {
          case -1:
              chenille++;
              document.getElementById("div1").append(oreen.cat + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
  
          case 1:
              chenille++;
              document.getElementById("div1").append(oreen.dog + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
        
          case 2:
                chenille++;
                document.getElementById("div2").append(oreen.sky + "<br />");
                nieva++;
                updateProgress(chenille, leray.length);
                tvmit_dieUp();
                break;
  
          case 3:
              chenille++;
              document.getElementById("div3").append(oreen.water + "<br />");
              tvmit_liveUp();
              updateProgress(chenille, leray.length);
              break;
      }
  
        OKTY(leray, chenille, aarsh, nieva);
      }
      return true;
    } catch (error) {
      console.log(error)
    }
  }
  envSoli();

UPDATE

My textarea has 10 lines that with the Jquery code I would send each one to my PHP and then return them to the divs in HTML.

The current code (Vanilla), only makes 1 request and dont send the result to the HTML. (But my PHP validation is correct, the problem is in the JS code).

How i can fix it? I put a image for reference: img

  • Don't try to create JSON with string concatenation in PHP. Put the values in an array and use `echo json_encode($array);` – Barmar Sep 09 '22 at 17:53

3 Answers3

0

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!

0

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])

Also, change:

      headers: { "Content-type": "application/json" }

to:

      headers: { "Content-type": "application/x-www-form-urlencoded" }

The content is being sent in URL-encoded format. PHP won't parse JSON automatically.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Don´t work ): in addition my textarea send aprox 10 lines in json to my php and the php divide the numbers – SadDeepLoper Sep 09 '22 at 17:50
  • See the update. You need to get rid of the `Content-type` header. – Barmar Sep 09 '22 at 17:55
  • It works! The request is now as it should be. It only makes one request and not all of them and I can't get them to return in their respective `
    `.
    – SadDeepLoper Sep 09 '22 at 18:43
  • I edited my question adding more details in both the original Jquery code and the other one. This is the complete code of the AJAX call. Could you check it? :( – SadDeepLoper Sep 09 '22 at 18:44
  • There's nothing in the original jQuery code that will make more than one request. It sounds like the problem is with how you're calling it. – Barmar Sep 09 '22 at 19:35
  • I understand, and with respect to not returning the result in the `
    ` do you think it is because of some error in my code? Am I returning it correctly?
    – SadDeepLoper Sep 10 '22 at 00:46
0

After many attempts I have succeeded. This is the final result. (Thanks to the user @Barmar):

const envSoli = async () => {
    try {
      let peticion = await fetch("data.php", {
        method: "POST",
        body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        cache: "no-cache
      });
      let oreen = await peticion.json();

        switch (oreen.enviando) {
          case -1:
              chenille++;
              document.getElementById("div1").append(oreen.cat + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
  
          case 1:
              chenille++;
              document.getElementById("div1").append(oreen.dog + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
        
          case 2:
                chenille++;
                document.getElementById("div2").append(oreen.sky + "<br />");
                nieva++;
                updateProgress(chenille, leray.length);
                tvmit_dieUp();
                break;
  
          case 3:
              chenille++;
              document.getElementById("div3").append(oreen.water + "<br />");
              tvmit_liveUp();
              updateProgress(chenille, leray.length);
              break;
      }
  
        OKTY(leray, chenille, aarsh, nieva);
      return true;
    } catch (error) {
      console.log(error)
    }
  }
  envSoli();