SELECT ANIDADOS

0

I make a ticket system in which when filling out my form of my main table tickets I have users and areas what I intend to do in my form > select is that when choosing an area, only the users that belong to that area appear .

I appreciate your help.

Ticket table structure (main)

id                Primaria  int(11)
title                       varchar(100)
process_1                   varchar(100)
process_2                   varchar(100)
category_id       Índice    int(11)
priority_id       Índice    int(11)
turn_id           Índice    int(11)
area_id           Índice    int(11)
status_id         Índice    int(11)
final_id          Índice    int(11)

Structure table area

area_id    Primaria    int(11)
name                   varchar(100)

Final table structure (users) I have the field id_area that belongs to the table area

 final_id       Primaria    int(11)
 name                       varchar(100)
 id_area        Índice      int(11)

Insert code

<?php	
	session_start();
	/*Inicia validacion del lado del servidor*/
	if (empty($_POST['title'])) {
           $errors[] = "Descripción vacío";
        } 
		
		 else if (
			!empty($_POST['title'])
			
		){


		include "../config/config.php";//Contiene funcion que conecta a la base de datos

		$title = $_POST["title"];
		$process_1 = $_POST["process_1"];
		$process_2 = $_POST["process_2"];
		$category_id = $_POST["category_id"];
		$priority_id = $_POST["priority_id"];
		$turn_id = $_POST["turn_id"];
		$area_id = $_POST["area_id"];
		$user_id = $_SESSION["user_id"];
		$status_id = $_POST["status_id"];
		$final_id = $_POST["final_id"];
		$kind_id = $_POST["kind_id"];
		$created_at="NOW()";

		// $user_id=$_SESSION['user_id'];

		$sql="insert into ticket (title,process_1,process_2,category_id,priority_id,turn_id,area_id,user_id,status_id,final_id,kind_id,created_at) value (\"$title\", \"$process_1\",\"$process_2\",\"$category_id\",$priority_id,$turn_id,$area_id,$user_id,$status_id,$final_id,$kind_id,$created_at)";

		$query_new_insert = mysqli_query($con,$sql);
			if ($query_new_insert){
				$messages[] = "Tu ticket ha sido ingresado satisfactoriamente.";
			} else{
				$errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con);
			}
		} else {
			$errors []= "Error desconocido.";
		}
    
    
 ?>

Code

<?php
  
	  $areas =mysqli_query($con, "select * from area order by name");
	  $finales =mysqli_query($con, "select * from final order by name");
    
	
?>


  <div> <!-- Modal -->
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg-add"><i class="fa fa-plus-circle"></i> Agregar Ticket</button>
    </div>
    <div class="modal fade bs-example-modal-lg-add" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">Agregar Tickets</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal form-label-left input_mask" method="post" id="add" name="add">
                        <div id="result"></div>
						
						
                        
						
						
					     <div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Usuario Final
                            </label>
                            <div class="col-md-9 col-sm-9 col-xs-12">
                                <select class="form-control" name="final_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                  <?php foreach($finales as $p):?>
                                    <option value="<?php echo $p['final_id']; ?>"><?php echo $p['name']; ?></option>
                                  <?php endforeach; ?>
                                </select>
                            </div>
                          </div>
						
						
						
						
						
						
						
						
						
						<div class="form-group">
                            <label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Area
                            </label>
                            <div class="col-md-9 col-sm-9 col-xs-12">
                                <select class="form-control" name="area_id" >
                                    <option selected="" value="">-- Selecciona --</option>
                                      <?php foreach($areas as $p):?>
                                        <option value="<?php echo $p['id']; ?>"><?php echo $p['name']; ?></option>
                                      <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
						
						
						
						
                       
						
                        <div class="ln_solid"></div>
						
						
                        <div class="form-group">
                            <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                              <button id="save_data" type="submit" class="btn btn-success">Guardar</button>
                            </div>
                        </div>  

						
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div> <!-- /Modal -->
    
asked by Carlos 01.08.2018 в 08:00
source

1 answer

0

I can think of 2 ways to do it so that you do not need to reload the page in each selection:

  • The easiest way to do this is to load all the users within the select, add them as clase the name of the zone and that by default keep all in display:none; . Then every time the user selects a zone simply do displayblock; ( I think it is another type of display that is added to an element of the select )
      

    This is a simple method to create, but it is also the slow method when loading, that is, if you have few users it is fine, however if you have many they will load all the time so you can slow down a lot. (I usually use it sometimes if I know that the amount is low)

In the file form.php

    <select name="areas" id="select-area">
        <?php
            // Hace tu peticion a la base de datos y almacenas ls areas
            $areas;  // Array que contiene las areas

            foreach ($areas as $area ) {
                $area_id = $area["area_id"];
                $name = $area["name"];

                echo "<option value=\"$area_id\">$name</option>";

            }
        ?>
    </select>


    <select name="usuarios" id="select-usuario">
        <?php
            // Hace tu peticion a la base de datos y almacenas los usuarios en un array
            $usuarios;  // Array que contiene los usuarios
            // escribes todos los usuarios
            foreach ($usuarios as $usuario ) {
                $final_id = $usuario["final_id"];
                $name = $usuario["name"];
                $id_area = $usuario["id_area"];
                echo "<option class=\"area-$id_area\"value=\"$final_id\">$name</option>";

            }

        ?>
    </select>

In the file form.js :

  

Use jQuery:

$(document).ready(function () {
    $("#select-area").change(function(){
        // Obtienes la nueva seleccion
        var areaSeleccionada = $(this).val();

        // Ocultas todos los usuarios
        $("#select-usuario>option").css("display","none");

        // Muestras los usuarios del area seleccionada
        $(".area-"+areaSeleccionada).css("display","block")
    });
});

In the styles, by default it must be the following line:

#select-usuario>option{
   display:none;
}




  • The other way is that in the select> of each zone the value=" " is the ID of each zone, then you need to prepare 2 blocks of code in 2 different files:
    codigo.js :
    In javascript using jQuery you make an ajax request to a file prepared to respond to it with the chosen data

    $.ajax({
        data: { "param": area_id},
        url: "usuariosZona.php",
        type: "POST",
        dataType: "json",
        // SI la peticion funciona y devuelve datos:
        success: function (datos) {
            // la variable 'datos' contiene las lineas del select.
            $.each(datos, function (i, usuarios) {
                // Por cada usuarios lo escribes en el select.
            })
        }
    });
    


usuariosZona.php :
You will receive the paramenter that we indicate and will return the data in JSON format

<?php
  // Recogera el parametro que le pases
  $id_area = $_POST["param"];  
  // es el archivo en el que tengo mi conexion con la base de datos
  include "../util/conexion.php"; 

  // La query que realizaras en la base de datos
  $query = "SELECT * FROM usuarios WHERE id_area=\"$id_area\"";
  // Ejecutas la query, la funcion bdQuery es un creada por mi
  // aunque puedes ejectura la query de la forma que te sea mas facil
  $result = bdQuery($query);

  // devuelves los datos en formato JSON
  echo json_encode($result->fetchAll());
?>

This would be the correct way to paralyze it if you have a lot of data, so that you do not have to load everything and only request the chosen areas.

  

If you had thought to do this only with PHP, it is possible although the page will be updated in each zone selection to load the users.

    
answered by 01.08.2018 в 08:55