skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

    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();
    

  2. 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!

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search