Modify variable value in script when clicking on a label

1

Good morning,

I'm working with a small script that runs when you click on label . By doing so, it activates or deactivates a checkbox type input, and based on this I want it to show one thing or another on the screen (if it has been subscribed or not).

The parameters are passed through AJAX so that the page is not reloaded, but I find that the variable in JS is not updated, it always has the same value, the funny thing is that the database updates it well

$agregar = $usuario;
$statement = $conexion->prepare("SELECT * FROM comentarios WHERE ID = :id");
$statement->execute(array(":id" => $hilo_asunto[0]['ID']));
$resultado_me_gusta = $statement->fetchAll();

$porciones = explode(";", $resultado_me_gusta[0]['suscritos']);

$contador = 0;

foreach ($porciones as $porcion) {
   if ($porcion ==  $agregar) {
      $contador++;
   }
}

if ($usuario != "null") {
   if ($contador == 0) {
      echo "<form class='' name='suscribe' id='suscribirse_" . $id . "' title='Suscripcion post' action='foro.php?foro=" . $foro ."&subforo=" . $subforo . "&hilo=Vamos%dale&ID=" . $id . "' method='post'>";
          echo "<input class='suscribe_box' type='checkbox' id='suscribe_" . $id . "' name='subs' checked>";
          echo "<label id='suscripcion_" . $id . "'  class='suscribirse' onclick='myFunction_suscribirse($id)' for='suscribirse_" . $id . "'>Suscribirse</label>";
          echo "<label id='suscripcion_oculto_" . $id . "'  class='label_oculto' onclick='myFunction_suscribirse($id)' for='suscribirse_" . $id . "'>Ya suscrito</label>";
   } else {
          echo "<form class='' name='suscribe' id='suscribirse_" . $id . "' title='Suscripcion post' action='foro.php?foro=" . $foro ."&subforo=" . $subforo . "&hilo=Vamos%dale&ID=" . $id . "' method='post'>";
          echo "<input class='suscribe_box' type='checkbox' id='suscribe_" . $id . "' name='subs' checked>";
          echo "<label id='suscripcion_" . $id . "'  class='label_oculto' onclick='myFunction_suscribirse($id)' for='suscribirse_" . $id . "'>Suscribirse</label>";
          echo "<label id='suscripcion_oculto_" . $id . "'  class='suscribirse' onclick='myFunction_suscribirse($id)' for='suscribirse_" . $id . "'>Ya suscrito</label>";
   }

   echo "</form>";

}

The script that runs:

<script>
        function myFunction_suscribirse(respuesta_id) {
            let suscribirse;
            var id_respuesta = respuesta_id;
               var d = document.getElementById("suscripcion_"+id_respuesta);
               var form = document.getElementById("suscribirse_"+id_respuesta);
               var respuesta_id = "respuesta_" + respuesta_id;

              if( $("#suscribe_"+id_respuesta).prop('checked') ) {
                  suscribirse = 1;
                  d.style.background = "transparent";
                  d.style.color = "#949494";
              } else {
                  suscribirse = 0;
                  form.style.background = "transparent";
              }

              console.log(suscribirse)

               $.ajax ({
                 type: 'POST',
                 url: 'proces_suscribe.php',
                 data: { "corazon": suscribirse, "id_respuesta":id_respuesta }
               });



          };
        </script>

At this point the variable suscribirse always has the value 1, when it should vary between 0 and 1 depending on whether the input of type checkbox is activated or not.

The file proces_suscribe.php:

<?php

session_start();

require 'admin/config.php';

try {
    $conexion = new PDO($bd_config['dbname'], $bd_config['usuario'], $bd_config['password'] );
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}


$heart = isset($_POST['suscribirse'])? $_POST['suscribirse'] : 0;
$like_id = isset($_POST['id_respuesta'])? $_POST['id_respuesta'] : 0;

if ($conexion) {

    $statement = $conexion->prepare("SELECT * FROM comentarios WHERE ID = :id");
    $statement->execute(array(":id" => $like_id));
    $resultado_me_gusta = $statement->fetchAll();

    $agregar = $_SESSION['usuario'];
    $todos_suscritos = $resultado_me_gusta[0]['suscritos'];

    $porciones = explode(";", $resultado_me_gusta[0]['suscritos']);

    $contador = 0;

    foreach ($porciones as $porcion) {
        if ($porcion ==  $agregar) {
            $contador++;
        }
    }

    //SI CONTADOR ES DISTINTO A 0 SIGNIFICA QUE YA HA DADO ME GUSTA, CON LO QUE HRBÍA QUE QUITARLO DE LA BAES DE DATOS PORQUE YA NO LE GUSTA

    if ($contador == 0) {
        $todos_suscritos .= $agregar . ";";

        $statement = $conexion->prepare("UPDATE comentarios SET suscritos = :agregar WHERE id = $like_id");
        $statement->execute(array(":agregar" => $todos_suscritos));

        //hay que quitarle uno porque siempre cuenta un array vacío...

        echo "<p>Ya estás suscrito</p>";



    } else {

        $a_borrar = $agregar . ";";
        $todos_suscritos = str_replace("$a_borrar","", $todos_suscritos);

        $statement = $conexion->prepare("UPDATE comentarios SET suscritos = :agregar WHERE id = $like_id");
        $statement->execute(array(":agregar" => $todos_suscritos));


        //hay que quitarle uno porque siempre cuenta un array vacío...

        echo "<p class='suscribirse'>Suscribirse</p>";


    }

}

?>

By not getting the script variable modified correctly I can not make the page with the correct content reload.

    
asked by JetLagFox 16.04.2017 в 00:42
source

1 answer

1

The PHP code you share (or rather the HTML it generates) has a problem: the label are pointing to the ID of the form ( 'suscribirse_" . $id . "' ), when they should be pointing to the checkbox ( 'suscribe_" . $id . "' ). As it points to the wrong ID, the checkbox box will always be checked (I guess you have it hidden somehow and that's why you do not see it) and the value of the variable suscribirse will always be 1.

This is your generated code without any modification, just assuming that the value of $i will be 1:

function myFunction_suscribirse(respuesta_id) {
  let suscribirse;
  var id_respuesta = respuesta_id;
  var d = document.getElementById("suscripcion_"+id_respuesta);
  var form = document.getElementById("suscribirse_"+id_respuesta);
  var respuesta_id = "respuesta_" + respuesta_id;

  if( $("#suscribe_"+id_respuesta).prop('checked') ) {
    suscribirse = 1;
    d.style.background = "transparent";
    d.style.color = "#949494";
  } else {
    suscribirse = 0;
    form.style.background = "transparent";
  }

  console.log(suscribirse)

  $.ajax ({
    type: 'POST',
    url: 'proces_suscribe.php',
    data: { "corazon": suscribirse, "id_respuesta":id_respuesta }
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form class='' name='suscribe' id='suscribirse_1' title='Suscripcion post' action='foro.php?foro=test&subforo=test&hilo=Vamos%dale&ID=1' method='post'>
  <input class='suscribe_box' type='checkbox' id='suscribe_1' name='subs' checked>
  <label id='suscripcion_1'  class='suscribirse' onclick='myFunction_suscribirse(1)' for='suscribirse_1'>Suscribirse</label>
  <label id='suscripcion_oculto_1'  class='label_oculto' onclick='myFunction_suscribirse(1)' for='suscribirse_1'>Ya suscrito</label>
</form>

As you can see, the label points to the form (the form ID is in for of the label ), so the value of the checkbox is never updated and will always be 1 (because it is marked by default).

If you make the label point to the checkbox instead, the checkbox will be checked / unchecked correctly, and the value of the variable suscribirse will change from 1 to 0, respectively:

function myFunction_suscribirse(respuesta_id) {
  let suscribirse;
  var id_respuesta = respuesta_id;
  var d = document.getElementById("suscripcion_"+id_respuesta);
  var form = document.getElementById("suscribirse_"+id_respuesta);
  var respuesta_id = "respuesta_" + respuesta_id;

  if( $("#suscribe_"+id_respuesta).prop('checked') ) {
    suscribirse = 1;
    d.style.background = "transparent";
    d.style.color = "#949494";
  } else {
    suscribirse = 0;
    form.style.background = "transparent";
  }

  console.log(suscribirse)

  $.ajax ({
    type: 'POST',
    url: 'proces_suscribe.php',
    data: { "corazon": suscribirse, "id_respuesta":id_respuesta }
  });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form class='' name='suscribe' id='suscribirse_1' title='Suscripcion post' action='foro.php?foro=test&subforo=test&hilo=Vamos%dale&ID=1' method='post'>
  <input class='suscribe_box' type='checkbox' id='suscribe_1' name='subs' checked>
  <label id='suscripcion_1'  class='suscribirse' onclick='myFunction_suscribirse(1)' for='suscribe_1'>Suscribirse</label>
  <label id='suscripcion_oculto_1'  class='label_oculto' onclick='myFunction_suscribirse(1)' for='suscribe_1'>Ya suscrito</label>
</form>
    
answered by 16.04.2017 / 06:42
source