Home > php > When dropdown menu selected fill textbox with data from database

When dropdown menu selected fill textbox with data from database

December 2Hits:2
Advertisement

I have a problem with my code. I am trying to fill a textbox with data from the database. It needs to show the price of the selected item in my dropdownmenu. But it is not working. I can fill my dropdownmenu but when I select an item in it, my textbox stays empty.

I am using the following table structure:

forms (   `id` int(11) NOT NULL AUTO_INCREMENT,   `sort` int(1) NOT NULL,   `name` varchar(100) NOT NULL,   `price` decimal(7,2) NOT NULL,   `tax` int(2) NOT NULL,   PRIMARY KEY (`id`) ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; 

// index.php

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "database";  // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {      die("Connection failed: " . $conn->connect_error); }   $sql = "SELECT * FROM database"; $result = $conn->query($sql);  if ($result->num_rows > 0) {      echo "<select class='form-control select2' id='product1' name='product1' onChange='getstate(this.value);' style='width: 100%;'>";      echo "<option selected disabled hidden value=''></option>";      // output data of each row      while($row = $result->fetch_assoc()) {                       echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";      }                    echo "</select>"; } else {      echo "0 results"; }  $conn->close();  ?> <html>  <!-- Your text input --> <input id="product_name" type="text">  </html>  <script> function getPrice() {      // getting the selected id in combo     var selectedItem = jQuery('.select2 option:selected').val();      // Do an Ajax request to retrieve the product price     jQuery.ajax({         url: 'get.php',         method: 'POST',         data: 'id=' + selectedItem,         success: function(response){             // and put the price in text field             jQuery('#product_name').val(response);           },         error: function (request, status, error) {             alert(request.responseText);         },     }); } </script> 

get.php

<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "database;  // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {      die("Connection failed: " . $conn->connect_error); }      $productId = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT);      $query = 'SELECT price FROM forms WHERE id=' . $product1;      $res = mysql_query($query);     if (mysql_num_rows($res) > 0) {         $result = mysql_fecth_assoc($res);          print($result['price']);      die(); } ?> 

Can someone help me to fix this?

Tags:php, ajax

Related Articles

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 15 q. 0.673 s.