2

I'm trying to update a text field (Price) whenever a drop-down menu (List of Products) item is selected. the text filed will show the selected item's price. I want to do this using ajax and i'm still new to this.

My code so far:

index.php

<?php
  include 'Connection.php';
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="Style.css">
  <title>Shopping Cart</title>
</head>

<body>
  <div id="mainPadding">
    <h1 class="Shopping Title">The Shopping Items</h1>
    <form class="form-horizontal">
      <fieldset class="border p-2">
        <legend class="w-auto">Contact Details:</legend>
        <div class="form-group">
          <label class="control-label col-sm-2" for="name">Name:</label>
          <div class="col-sm-3">
            <input type="name" required class="form-control" id="name" placeholder="Enter Your Name">
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="email">Email:</label>
          <div class="col-sm-3">
            <input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" class="form-control" required id="email" placeholder="e.g. [email protected]">
          </div>
        </div>
      </fieldset>
      <fieldset class="border p-2">
        <legend class="w-auto">Available Items:</legend>
        <div class="form-group">
          <label class="col-lg-3 control-label">Item:</label>
          <div class="col-sm-3">
            <div class="ui-select">
              <select id="ItemListDropDown" class="selectpicker" data-live-search="true">
                <div id="itemList">
                  <?php
                      $sql = "SELECT Product_Name FROM products WHERE Availability = 1";
                      $result = mysqli_query($con, $sql);
                      if (mysqli_num_rows($result) > 0)
                        while ($row = mysqli_fetch_assoc($result))
                          echo "<option>" . $row["Product_Name"] . "</option>";
                    ?>
                </div>
              </select>
            </div>
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="price">Price</label>
          <div class="col-sm-3">
            <input type="text" disabled class="form-control" id="priceTxt">
          </div>
        </div>
        <div class="form-group">
          <label class="control-label col-sm-2" for="price">Quantity (between 1 and 5):</label>
          <div class="col-sm-3">
            <input type="number" maxlength="1" min="1" max="5" class="form-control" id="priceTxt">
          </div>
        </div>
        <div class="form-group">
          <label class="col-md-3 control-label"></label>
          <div class="col-md-8">
            <input id="addToCart" type="button" class="btn btn-primary" value="Add to the Cart">
          </div>
        </div>
      </fieldset>
      <fieldset class="border p-2">
        <legend class="w-auto">Invoice Details:</legend>
        <div class="form-group">
          <table class="table table-striped" id="ItemTable">
            <thead>
              <tr>
                <th scope="col">Sr.</th>
                <th scope="col">Item Name</th>
                <th scope="col">Price</th>
                <th scope="col">Count</th>
                <th scope="col">Total</th>
                <th scope="col">Delete</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th scope="row"></th>
                <td id="ItemName"></td>
                <td id="Price"></td>
                <td id="Count"></td>
                <td id="Total"></td>
                <td id="DeleteButton"></td>
              </tr>
            </tbody>
          </table>
          <div class="form-group">
            <label class="col-md-3 control-label"></label>
            <div class="col-md-8">
              <input id="PrintAndSend" type="submit" class="btn btn-primary" value="Print and Send to Email">
            </div>
          </div>
        </div>
      </fieldset>
    </form>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  <script src="Javascript.js"></script>
</body>
</html>

Javascrpt.js

$(document).ready(function() {
  $("#ItemListDropDown").change(function() {
    $("#itemList").load("load-product.php")
    // $("#priceTxt").attr("value", price);
  });      
});

load-product.php

  <?php
include 'Connection.php';


$sql = "SELECT Product_Name FROM products WHERE Availability = 1";

$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
    while ($row = mysqli_fetch_assoc($result))
        echo "<option>" . $row["Product_Name"] . "</option>";
?>

I'm trying to do a few things using ajax, solving this will set me up for the rest.

3
  • What's this query supposed to do? $sql = "SELECT Price FROM products WHERE Product_Name = "; - Doesn't look right, especially when you just try to execute it on the next line Commented Apr 9, 2019 at 16:02
  • 1
    Please don't do this with Ajax, it is easier to save the product price in a data-price HTML attribute along with the products elements and change the price when the user changes the product on the client side. Commented Apr 9, 2019 at 16:08
  • @Alon Eitan , I'm trying to get the price from the database using the selected Product_name from the drop-down menu Commented Apr 9, 2019 at 16:19

1 Answer 1

1

Snake, you don't need Ajax to get your product price, instead just use a data-* attribute:

in your php (NOT the load-product.php file):

<?php
$sql = "SELECT Product_id, Product_Name, Product_price FROM products WHERE Availability = 1";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
echo "<option value='default' data-price='default'>Choose a item </option>";
while ($row = mysqli_fetch_assoc($result))
echo "<option value='{$row["Product_id"}' data-price='{$row["Product_price"]}'>" . $row["Product_Name"] . "</option>";
?>

then in your javascript do this to get your item price:

// JavaScript using jQuery
$(function(){
    $('#ItemListDropDown').change(function(){
       var selected = $(this).find('option:selected');
       var extra = selected.data('price'); 
       $("#priceTxt").val(extra); // set your input price with jquery
       $("#priceTxt").prop('disabled',false);//set the disabled to false maybe you want to edit the price
       ...
    });
});

// Plain old JavaScript
var sel = document.getElementById('ItemListDropDown');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-price');
var priceInput = document.getElementById('priceTxt');
priceInput.disabled = false;
priceInput.value =extra;

Hope it helps =)

Sign up to request clarification or add additional context in comments.

1 Comment

I removed the sentence that gives the meaning that this is an Ajax solution, if this is not what you meant tell me to roll it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.