sashavalentina Posted October 8, 2021 Share Posted October 8, 2021 I'm trying to fetch the result based on the users selection in the select element. But i do not know where is the mistake i made, it just can't seems to fetch the correct result. Here are my codes: <table class="table"> <thead class="text-primary"> <th style=" position: sticky;top: 0; background: white";> Product </th> <th style=" position: sticky;top: 0; background: white";> Name </th> <th style=" position: sticky;top: 0; background: white";> Avaliable Stock </th> <th style=" position: sticky;top: 0; background: white";> Item Price(RM) </th> <th style=" position: sticky;top: 0; background: white";> Insert Product Quantity </th> </thead> <tbody id="products"> <?php $product_id = $_REQUEST['id']; $ids = explode(",",$product_id); $ids = array_splice($ids, 0); foreach($ids as $product_id){ $sql = "SELECT *, products.id as product_id FROM products LEFT JOIN sellers ON products.seller_id = sellers.id WHERE products.id = '".$product_id."' ORDER BY product_created DESC "; $query = $conn->query($sql); { while ($row = $query->fetch_assoc()) { $max = $row['product_stock']; ?> <tr> <td> <?php echo $row['product_title']; ?> </td> <td> <?php echo $row['product_stock']; ?> <?php echo $row['product_unit']; ?> </td> <td> <div class="col-md-6"> <input type="number" name="cart_qty" step=".01" class="form-control text-center" required> </div> </td> <td> <select name="price_range" id="price_range" class="form-control"> <option value="price_range1" selected><?php echo $row['weight_range1']; ?> <?php echo $row['product_unit']; ?></option> <option value="price_range2"> <?php echo $row['weight_range2']; ?><?php echo $row['product_unit']; ?></option> <option value="price_range3"><?php echo $row['weight_range3']; ?><?php echo $row['product_unit']; ?></option> <option value="price_range4"><?php echo $row['weight_range4']; ?> <?php echo $row['product_unit']; ?></option> </select> </td> <td> <div class="col-12 my-auto">RM <span id="product_price"> <input type="hidden" name="cart_price" value="<?php echo $row['product_price1']; ?>"> <?php echo $row['product_price1']; ?> </span>/<?php echo $row['product_unit']; ?> </td> </tr> </div> </div> <?php } } } ?> </tbody> </table> I use AJAX method to POST the selection result, here are the codes <script> $(document).ready(function() { $('#price_range').on('change', function() { var product_id = <?php echo $product_id ?>; var price_range = this.value; $.ajax({ url: "includes/fetch-price.php", type: "POST", data: { product_id: product_id, price_range: price_range }, cache: false, success: function(result){ $("#product_price").html(result); // console.log(price_range); } }); }); }); </script> Here is my fetch-price.php <?php require_once "../session.php"; $product_id = $_POST["product_id"]; $price_range = $_POST["price_range"]; $sql = mysqli_query($conn,"SELECT * FROM products where id = '$product_id' "); $scrow = mysqli_fetch_array($sql); if($price_range == 'price_range1') { echo '<input type="hidden" name="cart_price" value="'.$scrow['product_price1'].'">', $scrow['product_price1']; } else if($price_range == 'price_range2') { echo '<input type="hidden" name="cart_price" value="'.$scrow['product_price2'].'">', $scrow['product_price2']; } else if($price_range == 'price_range3') { echo '<input type="hidden" name="cart_price" value="'.$scrow['product_price3'].'">', $scrow['product_price3']; } else if($price_range == 'price_range4') { echo '<input type="hidden" name="cart_price" value="'.$scrow['product_price4'].'">',$scrow['product_price4']; } ?> any form of help will be appreciated thanks! Quote Link to comment https://forums.phpfreaks.com/topic/313907-why-ajax-not-able-to-fetch-result/ Share on other sites More sharing options...
requinix Posted October 8, 2021 Share Posted October 8, 2021 3 hours ago, sashavalentina said: But i do not know where is the mistake i made, it just can't seems to fetch the correct result. You've told us that it does not do what you want it to do but you haven't told us what it does do. What do you expect to see happen? What do you actually see happen? What have you tried so far to debug this? Quote Link to comment https://forums.phpfreaks.com/topic/313907-why-ajax-not-able-to-fetch-result/#findComment-1590795 Share on other sites More sharing options...
Barand Posted October 8, 2021 Share Posted October 8, 2021 6 hours ago, sashavalentina said: var product_id = <?php echo $product_id ?>; That line in your onchange function concerns me. If it was generated when PHP was executing. how does it relate to the id of the product the user is clicking in the browser? 1 Quote Link to comment https://forums.phpfreaks.com/topic/313907-why-ajax-not-able-to-fetch-result/#findComment-1590798 Share on other sites More sharing options...
Strider64 Posted October 8, 2021 Share Posted October 8, 2021 I was bored today and decided to take a break from my own develop, so I decided to fool around with this and see if I could help. I don't know exactly what you are doing and I only used one database table to do this. However, I think what you are after can easily be modified? If not that's OK as I said I was bored. 😂 I don't know why you don't use MySQL to pull in the range values of the prices? I created a mythical Bicycle Shop called Rocket Bicycles : <table id="products"> <tr> <th colspan="4">The Rocket Bicycles Inventory</th> </tr> <tr> <th>Record</th> <th>Product</th> <th>Price ($)</th> <th>Quantity</th> </tr> </table> and I used Vanilla JavaScript (I find that is just as easy and is easily transferable) 'use strict'; (function () { let data = {}; /* The Following can easily be put into HTML via js */ data.min = 0; data.max = 2000.00; /* Handle General Errors in Fetch */ const handleErrors = function (response) { if (!response.ok) { throw (response.status + ' : ' + response.statusText); } return response.json(); }; const productCard = function (record){ /* Get the Table Id */ const table = document.getElementById('products'); /* Create the Table Row element */ const tr = document.createElement('tr'); /* Create the necessary Elements for the column data */ const id = document.createElement('td'); const product = document.createElement('td'); const price = document.createElement('td'); const quantity = document.createElement('td'); /* Append the Table Row element to the Table */ table.append(tr); /* Append the Column Row data to the Table Rows */ tr.append(id); tr.append(product); tr.append(price); tr.append(quantity); /* Assign the appropiate class to the table data row */ /* Give the appropiate table data the corresponding data */ id.classList.add('normal_format'); id.textContent = record.id; product.classList.add('product_format'); product.textContent = record.product; price.classList.add('money_format'); price.textContent = "$" + record.price.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); quantity.classList.add('normal_format'); quantity.textContent = record.quantity; }; /* Success function utilizing FETCH */ const inventoryUISuccess = function (records) { /* Grabing the record data from the Database Table * and assigning the value of the objects to the * HTML table using a forEach statement in * Vanilla JavaScript. */ records.forEach(record => productCard(record)); }; /* If Database Table fails to load then hard code the correct answers */ const inventoryUIError = function (error) { console.log("The Darn Database Table did not load", error); }; /* create FETCH request for check answers */ const price_range = function (url, succeed, fail) { fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data) }) .then((response) => handleErrors(response)) .then((data) => succeed(data)) .catch((error) => fail(error)); }; price_range('rockets_inventory.php', inventoryUISuccess, inventoryUIError); })(); the PHP for the "Fetching of the Data": <?php require_once 'assets/config/config.php'; /* Makes it, so we don't have to decode the json coming from javascript */ header('Content-type: application/json'); /* * The below must be used in order for the json to be decoded properly. */ try { $data = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { } /* * Grab the database table data that meets the price requirements */ $sql = 'SELECT id, product, price, quantity FROM rocket_bicycles WHERE price >= :min AND price <= :max ORDER BY price '; $stmt = $pdo->prepare($sql); // Prepare the query: $stmt->execute(['min' => (float)$data['min'], 'max' => (float)$data['max']]); // Execute the query with the supplied data: $result = $stmt->fetchAll(PDO::FETCH_ASSOC); /* * If everything validates OK then send success message to Ajax / JavaScript */ if (isset($result)) { output($result); } else { errorOutput('There is a darn problem!'); } /* * Throw error if something is wrong */ function errorOutput($output, $code = 500) { http_response_code($code); try { echo json_encode($output, JSON_THROW_ON_ERROR); } catch (JsonException) { } } /* * After converting data array to JSON send back to javascript using * this function. */ function output($output) { http_response_code(200); try { echo json_encode($output, JSON_THROW_ON_ERROR); } catch (JsonException) { } } and here's the SQL for the database table -- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost:8889 -- Generation Time: Oct 08, 2021 at 11:24 PM -- Server version: 5.7.34 -- PHP Version: 8.0.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; -- -- Database: `php_sandbox` -- -- -------------------------------------------------------- -- -- Table structure for table `rocket_bicycles` -- CREATE TABLE `rocket_bicycles` ( `id` int(11) NOT NULL, `product` varchar(60) DEFAULT NULL, `price` float(6,2) NOT NULL, `quantity` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `rocket_bicycles` -- INSERT INTO `rocket_bicycles` (`id`, `product`, `price`, `quantity`) VALUES (1, 'Banana Rocket', 499.99, 5), (2, 'Pink Lady ', 499.99, 8), (3, 'Speed Demon', 999.98, 2), (4, 'Quick Silver', 1500.00, 1), (5, 'Lucky Lady', 300.00, 7); -- -- Indexes for dumped tables -- -- -- Indexes for table `rocket_bicycles` -- ALTER TABLE `rocket_bicycles` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `rocket_bicycles` -- ALTER TABLE `rocket_bicycles` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; COMMIT; and a little bit of css: #products { font-family: Arial, Helvetica, sans-serif; border-collapse: collapse; width: 90%; margin: 0 auto; } #products td, #products th { border: 1px solid #ddd; padding: 8px; } #products tr:nth-child(even) { background-color: #f2f2f2; } #products tr:hover { background-color: #ddd; } #products th { padding-top: 12px; padding-bottom: 12px; text-align: center; background-color: #04AA6D; color: white; } .normal_format { text-align: center; width: 6.250em; } .product_format { text-align: left; width: 6.250em; } .money_format { width: 3.125em; text-align: right; } Sorry for the long post, but I hope it helps: 1 Quote Link to comment https://forums.phpfreaks.com/topic/313907-why-ajax-not-able-to-fetch-result/#findComment-1590812 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.