1

in my code, a number is entered in a <textarea> that is sent by AJAX to validate it randomly with PHP (using rand()) and then I return the same number to a <div> in HTML plus the word correct or incorrect as the case may be.

The problem is that if I type the same number in the <textarea> and send it, it obviously returns a different value than the first one.

I would like to make that only in that session or (unless the user refreshes the tab) the value is the same even if I send it many times. For example if I send 12345678, if the first time the algorithm gives me "correct" then it stays the rest of the times the user makes the request.

Could you help me? I am just starting to try things with AJAX, I don't know much about PHP. I am just learning.

I attach parts of my code. Jquery:

updateTextBox(prueba[revisar]);
  ajaxCall = $.ajax({
    url: "miarchivo.php",
    dataType: "json",
    cache: false,
    type: "POST",
    beforeSend: function (nautia) {
      $("#checar").html("<img src='loading.gif'/>");
    },
    data: "ajax=1&do=check&lista=" + encodeURIComponent(prueba[revisar]),
    success: function (datos) {
      switch (datos.enviar) {
        case 0:
          revisar++;
          $("#div1").append(datos.largo + "<br />");
          updateProgress(revisar, prueba.length);
          erroneos();
          break;

        case 1:
          revisar++;
          $("#div2").append(datos.num2 + "<br />");
          updateProgress(revisar, prueba.length);
          erroneos();
          break;

        case 2:
          revisar++;
          $("#div3").append(datos.num3 + "<br />");
          nieva++;
          updateProgress(revisar, prueba.length);
          corectos();
          break;
      }

Part of my PHP Code:

<?php
$numPrincipal = $_POST["lista"] . "|";
$numPrincipal = str_replace("Numero", "", $numPrincipal);
$numPrincipal = str_replace("NUMERO", "", $numPrincipal);
if ($numPrincipal == 0) {
    header("location: /");
    return false;
}
$numPrincipal = str_replace(" ", "", $numPrincipal);
$quitarSimb = str_replace("|", "", $numPrincipal);
$largo = strlen($quitarSimb);
$empiezaCon = substr($quitarSimb, 0, 1);
if ($empiezaCon == 1) {
    if ($largo === 10) {
        $num = substr($quitarSimb, 0, 10);
    }
    if ($largo < 10 || $largo > 15) {
        echo '{"enviar":0,"largo":"<span class=text-danger>Está muy largo</span>' . $numPrincipal . '"}';
        return false;
    }
}
$randomNmr = rand(0, 7);
if ($randomNmr == 1) {
    echo '{"enviar":1,"num2":"<span class=text-danger>erroneo</span>' . $numPrincipal . '"}';
    return false;
}
if ($randomNmr == 2) {
    echo '{"enviar":2,"num3":"<span class=text-primary>correcto</span>' . $numPrincipal . '"}';
    return false;
}

?>
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Use a session variable. Then when they call the function again, check if the session variable is set and return that. Otherwise generate a random number, assign it to the session variable, and return it. – Barmar Sep 06 '22 at 01:15
  • @Barmar the PHP session wouldn't expire on page reload without removing the cookie – Phil Sep 06 '22 at 01:22
  • Save it in a global variable in JavaScript, and don't make the AJAX call again. – Barmar Sep 06 '22 at 02:18
  • @Barmar can you explain me? please – SadDeepLoper Sep 07 '22 at 10:32

2 Answers2

0

Store the results of each query in a cache variable. A Map is an excellent option for this.

Before you make a request, check the cache for an existing value.

const cache = new Map();

// example function for handling input
function handleInput(value) {
  if (!cache.has(value)) {
    $.ajax({ /* ... */ }).done(function(datos) {
      cache.set(value, datos);
      handleResponse(datos);
    });
  } else {
    handleResponse(cache.get(value));
  }
}

function handleResponse(datos) {
  // switch(datos.enviar) { ...
}
Phil
  • 157,677
  • 23
  • 242
  • 245
0

Use an object to hold the values returned by the AJAX call for each value of prueba[revisar]. Then you can check if the saved value is saved, and not make the AJAX call.

I've split the code that displays the result of the AJAX call out to a separate function, so it can be called either in the success: function or directly.

function display_datos(prueba, datos) {
  switch (datos.enviar) {
    case 0:
      revisar++;
      $("#div1").append(datos.largo + "<br />");
      updateProgress(revisar, prueba.length);
      erroneos();
      break;

    case 1:
      revisar++;
      $("#div2").append(datos.num2 + "<br />");
      updateProgress(revisar, prueba.length);
      erroneos();
      break;

    case 2:
      revisar++;
      $("#div3").append(datos.num3 + "<br />");
      nieva++;
      updateProgress(revisar, prueba.length);
      corectos();
      break;
  }
}

var saved_datos = {};

if (saved_datos[prueba[revisar]]) {
  display_datos(prueba, saved_datos[prueba[revisar]]);
} else {
  ajaxCall = $.ajax({
    url: "miarchivo.php",
    dataType: "json",
    cache: false,
    type: "POST",
    beforeSend: function(nautia) {
      $("#checar").html("<img src='loading.gif'/>");
    },
    data: {
      ajax: 1,
      do: 'check',
      lista: prueba[revisar]
    },
    success: function(datos) {
      saved_datos[prueba[revisar]] = datos;
      display_datos(prueba, datos);
    }
  });
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Apparently everything is fine, but I can't get it to work because it shows up in the console: `Uncaught TypeError: saved_datos is not a function` Do you know why? The line that marks the error is this one: `var saved_datos = {};` :c – SadDeepLoper Sep 08 '22 at 16:35
  • Sorry, that was a typo, it should be `saved_data[...]` not `saved_datos(...)` – Barmar Sep 08 '22 at 16:37
  • I get the same error =( the console says thats `saved_data` is not a function – SadDeepLoper Sep 08 '22 at 16:50
  • That can't be, you must not be running the fixed code. – Barmar Sep 08 '22 at 16:51
  • When you click on the line number in the error message it should show you the code. Make sure it says `if (saved_datos[prueba[revisar]]) {` like I changed it. – Barmar Sep 08 '22 at 16:51
  • My bad, thanks a lot my friend! It works perfectly! One thing, if I wanted to use that code for multiple lines in the textarea, how could I do it? An apology for the inconvenience I give you – SadDeepLoper Sep 08 '22 at 17:19
  • You'll need a loop. This gets complicated because of the asynchronous AJAX calls. See https://stackoverflow.com/questions/1151598/how-to-make-all-ajax-calls-sequential for example – Barmar Sep 08 '22 at 17:22