jeiidii
jeiidii

Reputation: 87

select from dropdown and show details from database using php

i already search for this question but the result is a litte confusing because today is my first time to encounter ajax and most answer is ajax. so i decided to post a question which is my work and trying to have someones help from here to guide me about ajax. this is for my project need some help please

this is my query for getting the values from database and display it to my dropdownlist

<?php
include('config.php');

    $sql="SELECT food FROM menu";
    $lists=mysql_query($sql);
?>

this is my dropdown list... i fetch data from my database to have my values in dropdown listenter image description here

<select name="fname" id='mySelect' value='Foodname'>
        <?php
                    while($food = mysql_fetch_array($lists)) {
                       echo '<option value='.$food['food'].'>'.$food['food'].'</option>'; 
                    }
                    echo '</select>';

        ?>

now i want to show the price of the selected food in the dropdown list.. i want it to show in input text so i am able to edit it if i want to

enter image description here

<input type='text' class="form-control" name='prc'>

this is my database enter image description here

Upvotes: 1

Views: 4747

Answers (1)

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

for select options give value as the database Id, like this

echo '<option value='.$food['id'].'>'.$food['food'].'</option>'; 

considering as id to be autoincrement column in DB.

Then write ajax like this.

$(document).ready(function() {
    $("#mySelect").change(function(){
        var val = $('#mySelect option:selected').val();    
        $.ajax({
            url: "path to php file to get the price",
            type: "POST",
            dataType: "HTML",
            data: {"id": val}
            async: false,
            success: function(data) {
              // for textbox add id as price
                 $("#price").val(data);// data will have the price echoed in somefilename.php          
            }
      }); 

    });
});

Lets say the url in ajax is somefilename.php

so in somefilename.php, yyou shud write query like this

<?php
    include('config.php');
    $id = $_POST['id'];//same name as in ajax data
    $sql="SELECT price FROM menu where id = $id";

    // echo the price here
?>

What ever you echo here, it will come in ajax success function with parameter 'data', then you can assign to the required textbox as i have done in success function()

Upvotes: 2

Related Questions