fill fields of a form with data from a mysql bd when selecting a select

0

the idea is that by clicking on any option of a select depending on this I fill in the fields of my form I am working with php, mysql: this is my select

<select name="ruta" id="ruta" class="form-control" onchange="showService(this.value)">
        <?php 
          $link = mysqli_connect("localhost", "root", "");
          mysqli_select_db($link, "stp17");
          $tildes = $link->query("SET NAMES 'utf8'"); //Para que se muestren las tildes correctamente
          $result = mysqli_query($link, "SELECT * FROM rutas");
          while ($filas = mysqli_fetch_array($result)){
            ?>
            <option value="<?php echo $filas['id']; ?>"><?php echo $filas['nomCorto']; ?></option>
            <?php                 
          }
          mysqli_free_result($result);
          mysqli_close($link);
        ?>
      </select>

In this div

<div id="nomCorto"></div>

alamaceno the data but I do not know how to put them in text boxes

Script

function showService(str) {
if (str=="") {
  document.getElementById("nomCorto").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("nomCorto").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","getservice.php?service="+str,true);
xmlhttp.send();

}

and this is my php file

    <?php
$link = mysqli_connect("localhost", "root", "");
   mysqli_select_db($link, "stp17");

$service = $_GET['service'];

$query = mysqli_query($link,"SELECT * FROM rutas WHERE id = '".$service."'");


while($row = mysqli_fetch_array($query)) {
?>
<p><?php echo $row['descripcion']; ?></p>
<?php
}

echo "</table>";

mysqli_close($link);
?>
    
asked by Jose Luis GP 06.03.2017 в 21:01
source

1 answer

1

ABOUT YOUR CODE
1. Nothing is understood, because it is very disorganized.

SUGGESTION USING AQUA DE JQUERY
1. Create a form that contains a Select, it must have an ID.
2. Create a DIV with an ID inside the form.
2. Use JQuery document ready and implement ajax send to your php file using POST.
3. In the PHP captures the data with POST.
4. Make the query using MySQLi.
5. With the data you obtain, you can create a String with the "new" elements that you want to have form as if you were in HTML and return it to AJAX with Echo.
6. The returned results you put in the div that you created with AJAX.

This method works for me.

NOTE: Remember that by doing this the "new" elements are dynamic unlike the select that you created before which is static. In order for the new elements to respond to events in the JQuery, you must use "On" to delegate events.

IF YOU ARE INTERESTED, YOU NOTIFY ME TO PLACE AN EXAMPLE CODE

    
answered by 14.03.2017 в 06:08