Passing a variable from Jquery to PHP ($_POST)

i´m doing a website for managing a school centre and i have a doubt i wish you can to solve it.

I have this code:

login.php

<!doctype html>
<html lang="es">
<head>
<meta charset="iso-8859-1" />
</head>

<body>

<form action="comprobacionlogin_usuario.php" method="POST">
  <table border="1">
  <tr>
    <th>Nombre de usuario</th>
    <td><input type="text" name="usuario"  autocomplete="off" required></td>
  </tr>
  <tr>
     <th>Contrase&ntilde;a</th>
     <td><input type="password" name="contrasena"  autocomplete="off" required></td>
     </tr>
  <tr>
      <td></td>
      <td><input type="submit" value="Enviar"></td>
  </tr>

</table>
</form>
¿No eres usuario? Pulsa <a href="altanuevoprofesor.php">aqu&iacute;</a>
</body>
</html>

nuevo_horario.php

<?php

session_start();
$curso=$_POST['curso'];
$clase=$_POST['clase'];
?>

<html lang="es">
    <head>
    <meta charset="iso-8859-1">
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="administrar_filas.js"></script>
    <link rel="stylesheet" type="text/css" href="estilo_botones_tabla.css">
    Horario
    </head>
    <body>
    <div id="elementos">
    <form id="datos" action="procesar_horario.php" method="post">
    <table border="1" id="tabla">
    <thead>
    <tr>
    <td>Hora</td>
    <td>Lunes</td>
    <td>Martes</td>
    <td>Mi&eacute;rcoles</td>
    <td>Jueves</td>
    <td>Viernes</td>
    </tr>
    </thead>

    <tbody>
    <tr class="fila-base">
    <td><input type="text" name="hora_0" placeholder="Hora_0"></td>
    <td><input type="text" name="asignatura_lun_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_lun_0"placeholder="Id_profesor"></td>
    <td><input type="text" name="asignatura_mar_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_mar_0"placeholder="Id_profesor"></td>
    <td><input type="text" name="asignatura_mie_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_mie_0"placeholder="Id_profesor"></td>
    <td><input type="text" name="asignatura_jue_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_jue_0"placeholder="Id_profesor"></td>
    <td><input type="text" name="asignatura_vie_0" placeholder="Asignatura"><br><input type="text" name="id_usuario_vie_0"placeholder="Id_profesor"></td>
    <td class="eliminar">Eliminar</td>
    </tr>
    <input type="hidden" name="curso" id="curso" value="<?php echo $curso ?>">
    <input type="hidden" name="clase" id="clase" value="<?php echo $clase ?>">
    </tbody>
    </table>

    <input type="button" id="agregar" value="Agregar fila" />
    <input type="submit" id="enviar"  value="Enviar">

    </form>
    </div>
    <?php
        $conexion = mysql_connect("localhost", "alonsosjumper", "alonsosjumper") or die('No se pudo conectar: ' . mysql_error());
echo '<br>Conexi&oacuten satisfactoria<br>';

mysql_select_db("proyecto", $conexion) or die('No se pudo seleccionar la base de datos');

    $consulta= "select id_usuario, nombre, apellidos from usuarios where tipo_usuario='profesor' order by id_usuario";
    $resultado= mysql_query($consulta);

    echo ' <p>Lista de profesores</p>
    <table border="1" width="auto">
    <tr><td>Id_usuario</td><td>Nombre</td><td>Apellidos</td></tr>';

    while($fila = mysql_fetch_array($resultado))
{

    echo "<tr><td>".$fila['id_usuario']."</td><td>".$fila['nombre']."</td><td>".$fila['apellidos']."</td></tr>";
}

    ?>
    </body>
</html>

procesar_horario.php

<?php

session_start();

//I wanna have here the variable "cuentaInputs" to use it in the for.

$conexion = mysql_connect("localhost", "alonsosjumper", "alonsosjumper") or die('No se pudo conectar: ' . mysql_error());
echo '<br>Conexi&oacuten satisfactoria<br>';

mysql_select_db("proyecto", $conexion) or die('No se pudo seleccionar la base de datos');

for($i=0; $i<$cuentaInputs; $i++) {
    for($j=1; $j<6; $j++)
{
    if($j==1)
    {
        $asignatura=$_POST["asignatura_lun_".$i];
        $id_usuario=$_POST["id_usuario_lun_".$i];
        $hora=$_POST["hora_".$i];
    $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

    echo $consulta;
    }
    if($j==2)
    {
        $asignatura=$_POST["asignatura_mar_".$i];
        $id_usuario=$_POST["id_usuario_mar_".$i];
        $hora=$_POST["hora_".$i];
    $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

    echo $consulta;
    }
    if($j==3)
    {
        $asignatura=$_POST["asignatura_mie_".$i];
        $id_usuario=$_POST["id_usuario_mie_".$i];
        $hora=$_POST["hora_".$i];
    $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

    echo $consulta;
    }
    if($j==4)
    {
        $asignatura=$_POST["asignatura_jue_".$i];
        $id_usuario=$_POST["id_usuario_jue_".$i];
        $hora=$_POST["hora_".$i];
    $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

    echo $consulta;
    }
    if($j==5)
    {
        $asignatura=$_POST["asignatura_vie_".$i];
        $id_usuario=$_POST["id_usuario_vie_".$i];
        $hora=$_POST["hora_".$i];
    $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

    echo $consulta;
    }
    }


    }
$resultado = mysql_query($consulta);

mysql_close($conexion);


?>

administrar_filas.js

$(function(){
    var cuentaInputs = ($(".fila-base").length);

    $("#agregar").on('click', function(){
        $('#tabla > tbody:last').after('<tr><td><input type="text" name="hora'+cuentaInputs+'" placeholder="Hora"></td><td><input type="text" name="asignatura_lun_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_lun_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_mar_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_mar_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_mie_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_mie_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_jue_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_jue_'+cuentaInputs+'"placeholder="Profesor"></td><td><input type="text" name="asignatura_vie_'+cuentaInputs+'" placeholder="Asignatura"><br><input type="text" name="id_usuario_vie_'+cuentaInputs+'"placeholder="Profesor"></td><td class="eliminar">Eliminar</td></tr>');
        cuentaInputs++;

    });

    // Evento que selecciona la fila y la elimina 
    $(document).on("click",".eliminar",function(){
        if (cuentaInputs>1)
        {
        var parent = $(this).parents().get(0);
        $(parent).remove();
        cuentaInputs--;

        }
        else
            alert("No se puede eliminar la ultima fila");
    }); 

});

I would like to have the variable "cuentaInputs" in "procesar_horario.php" to use it in for. I need it for a dynamic timetable i´m doing which it´s possible to add or remove rows.

How I can to pass the variable cuentaInputs from Jquery to PHP?

Thanks a lot!

Upvotes: 0

Views: 1357

Answers (3)

Mohit
Mohit

Reputation: 2249

after reading your comment. it seems you are trying to send a rows of data. insted of putting for element name and id like the following

name="asignatura_lun_'+cuentaInputs+'"

use array indexing

name="asignatura_lun['+cuentaInputs+']"

this way you'll get following arrays in php

$_POST['hora']
$_POST['asignatura_lun']
$_POST['id_usuario_lun']   
//likewise for mar, mie, jue and vie

at the php side loop for hora array using foreach

foreach($_POST['hora'] as $key => $value)  //use $key for referencing other arrays.
{
  for($j=1; $j<6; $j++)
  {
    if($j==1)
    {
        //use $key for referencing other arrays.
        $asignatura=$_POST["asignatura_lun"][$key];
        $id_usuario=$_POST["id_usuario_lun"][$key];
        $hora=$value;   //$value is current horra
        $consulta = "INSERT INTO horarios (asignatura, curso, clase, fecha, hora, id_usuario) VALUES ('$asignatura', '$curso','$clase','lunes','$hora','$id_usuario')";

        echo $consulta;
    }

    //same for other weekdays
  }
}

Reference: Read this question and answer.


Before Edit :

I really cant understand most of your code. Please try to use english identifiers. but on a brief look, using a hidden input element should solve your problem. add this in your form which submits to procesar_horario.php

<input type='hidden' name='cuentaInputs' id='cuentaInputs'/>

you can update its value whenever you update cuentaInputs.

$('#cuentaInputs').val(cuentaInputs);

Upvotes: 1

Loenix
Loenix

Reputation: 1090

There is no sign of jQuery in your question.
If you are developing an application, make sure to understand how it works or your project is doomed to failure.

jQuery is a library for Javascript, a client side programming language, that means this is the browser the user uses that is running the code (as HTML and CSS).
PHP is a programming language running on server side, that means clearly this is running on the server.
So you can not easily interact between them just with your own mind, there is no magic in it.

Browsers can natively submit a form with a submit button.
If you want do it with jQuery (or pure Javascript), you can trigger manually the submission (e.g with jQuery $("form").submit()).
You can also use it to send data to the server with AJAX features (e.g with jQuery $.post({howifeelit:"good"})) and the server gives you some results (HTTP inside).

Other advices:

  • Prefer the international language for programming. (even if you love you mother tongue, i understand) This is more understandable and re-usable.
  • Prefer PDO to old obsolete mysql_* functions.
  • If you persist, please use mysql_fetch_assoc() instead of mysql_fetch_array(), this is lighter and you get what you want.
  • Look at one of the million tutorial on the web to learn basics. (look at PDO, include, POST and framework keywords)

Upvotes: 0

tomca32
tomca32

Reputation: 1140

Jquery's ajax method will send some value to PHP like this.

$.ajax({
  type:'POST',
  url:'procesar_horario.php',
  data: {q: putVariableHere}, //put a variable you want to pass here
  success: function (response) {
    console.log('yey, we passed the variable');
  }
});

PHP:

<?php

session_start();

//I wanna have here the variable "cuentaInputs" to use it in the for.
$cuentaInputs = $_POST['q'];

Upvotes: 0

Related Questions