select an element in a select and bring the id to perform search in mysql

0

<div id="leftcolumn">
	 	  	<form class="form-register" action="actualizar_insumo.php" method="post">
		 		<h3>MODIFICAR INSUMOS MEDICOS</h3>
		 		<div class="contenedor-inputs">
		 			<input type="hidden" name="cod_item" value="1">
		 			<div class="contenedor-labels-100">NOMBRE DEL INSUMO</div>
			 		<div class="select1">
							<select name="insumos" id="item" required>
								<option value="">Seleccione</option>
								<?php
								 	 $datos = "SELECT id,cod_item,nombre,presentacion FROM insumos WHERE cod_item LIKE 'im%'";
	         						 $ins_med = mysqli_query($conexion,$datos);

	         						 while ($ins_medicos = mysqli_fetch_array($ins_med)) {

										echo "<option value='".$ins_medicos[id]."''>".$ins_medicos['nombre']." / ".$ins_medicos['presentacion']."</option>";
									}
	            				?>
							</select>
					</div>
					<div class="contenedor-labels-100">PRESENTACION</div>
			 		<input type="text" class="input-100" name="presentacion" id="presentacion">
			 		<div class="contenedor-labels-45">FECHA DE VENCIMIENTO</div>
			 		<div class="contenedor-labels-45">CANTIDAD</div>
			 		<input type="date" class="input-45" name="fecha_venc" id="fecha_venc">
			 		<input type="text" class="input-10" name="stock" id="stock">
			 		<div class="contenedor-labels-100"></div>
			 		<button type="submit" class="btn-circular"><img src="imagenes/enviar2.png"></button>
			 	</div>
			 </form>
    
asked by Paul Bazo 15.04.2018 в 23:19
source

2 answers

0

For what you have said in your comments, you are trying to do it with a js function. A pity that you could not be more explicit at the time of formulating the question and have shown better the structure of the code, but it is already.

Based on what you have done and need to do, the value of the id of each product must be in the value="" of each <option></option> of your select, leaving something like this:

<select name="mi-select" id="mi-select">
 <option value="<?php echo $ins_medicos['id'] ?>"></option>
</select>

This does not change much with what you have, only that you have to place a id to the select so that you use it as an identifier and through ajax manage the value it brings and thus be able to make the other query you need.

Now you would have to perform a function that when selecting a product of the select you fill in some text fields that will contain, I suppose, the information of that product.

This way you can do it:

SCRIPT PHP

Here you can handle it with a json object that contains all the results according to that id

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){

 $id = $_POST['mi-select'];

 //NO SE COMO TENGAS TU CONEXIÓN A LA BD, NI QUE TIPO DE CONEXIÓN UTILICES, PERO AQUÍ IRÍA

 $sql = $db->query("SELECT * FROM tabla WHERE id = "$id" LIMIT 1");
  if($sql->num_rows>0){
    while($row=$sql->fetch_assoc()){
     $filas[] = $row;
    }
    echo json_encode(array('response'=> true, 'datos'=> $filas)); //MANDAMOS EL ARREGLO CON LOS DATOS EN UN OBJETO DE JSON
  } else {
    echo json_encode(array('response'=> false)); //AQUÍ PUEDES MOSTRAR UN AVISO DE QUE NO SE ENCONTRÓ NADA
  }
 } else {
   header('location:index.php');
 }

AJAX FUNCTION

$(document).ready(function(){
  $('#mi-select').on('change',function(){
    var id = $("#mi-select").val()
    $.ajax({
        type: 'POST',
        url:'ver_info.php', //NOMBRE DEL ARCHIVO A DONDE IRA LA PETICIÓN AJAX
        dataType: 'json',
        data:{'id':id}
    })
    .done(function(result){
      //PREGUNTAS SI CONSIGUIO DATOS EL PHP
      if(result.response == true){
        //EN ESTA PARTE ES DONDE MUESTRAS LOS VALORES EN LOS INPUTS
        $("#input1").val(datos.nombre);
        $("#input2").val(datos.presentacion);
      } else {
        alert("El producto no existe, o X cosa");
      }
    })
  })
});

I'll explain a little, the form that contains the select with your list of products you're going to send with ajax to php, php will be responsible for retrieving the data that ajax sent that will be the variable POST containing the id of the product, you make the query and if you find results you save everything in an array which will go to a json object, and having this you can show them dynamically in the inputs.

It should be noted that this query is vulnerable to SQL injection, but since I do not know how you are working, I have put it in that way.

Finally, if you are going to make the ajax script in an external file, remember that you must invoke it in the file where your form is after the invocation to the Jquery library, in this way:

<script src="jquery.min.js"></script>
<script src="funciones.js"></script>
    
answered by 16.04.2018 в 00:34
-2

function showItem (str) {

if (str == "") {   document.getElementById ("txtHint"). innerHTML="";   return; }

if (window.XMLHttpRequest) {// code for IE7 +, Firefox, Chrome, Opera, Safari   xmlhttp = new XMLHttpRequest (); } else {// code for IE6, IE5   xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function () {   if (xmlhttp.readyState == 4 & & xmlhttp.status == 200) {     document.getElementById ("txtHint"). innerHTML = xmlhttp.responseText;     } }

xmlhttp.open ("GET", "data_insumo.php? id_item=" + str, true); xmlhttp.send (); }

    
answered by 17.04.2018 в 13:04