How to show ajax data into while loop? - php

I have fetched some car brand names in a while loop and then for each brand name I make a select menu for the car names in another while loop by using the "brand id" as foreign key. And then I want to show the car names in a box each time someone changes the dropdown select options. Here's my code below :
$query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id));
<select name="car" id="car">
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
<?php
} // Closing Inner while loop
?>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
} // Closing outer while loop
In the ajax.php I have written the following code to echo the car name
$carName = $_POST['car'];
echo $carName;
But the issue is - it is just executed for the first option selected inside first inner loop of the first outer loop. I mean the ajax code only runs for the first iteration of the both loops.
I also tried to make the select menu and the result div unique by adding the "brand id" as follow :
<div id="result<?php echo $brand_id ?>"></div>
and
<select name="car" id="car<?php echo $brand_id ?>">
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
</select>
and also the ajax as following :
$('#car<?php echo $brand_id ?>').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result<?php echo $brand_id ?>').html(data);
}
});
But it didn't work. Please suggest your best possible solutions. Thank you.

Try my code
$query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result<?php echo $brand_id;?>"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id));
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<select name="car[]" id="car<?php echo $row2->id ?>">
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car<?php echo $row2->id ?>').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
console.log(data);
$('#result<?php echo $brand_id;?>').html(data);
}
});
});
});
</script>
<?php
}
}

The select and ajax code should be out of while loop. just check the code below
<?php $query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id)); ?>
<select name="car" id="car">
<?
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
<?php
} // Closing Inner while loop
?>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
} // Closing outer while loop
?>
``

You need not call ajax() in a while loop.
Simply you can call .change() on
<select name="car" onchange="getCar(this.value)">
<script type="text/javascript">
function getCar(car) {
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html('');
$('#result').html(data);
}
});
}
</script>
<div id="result"></div>

Related

Not Getting a POST value from ajax

I have a select dropdown and a textfield in my form. So i tried using $.ajax whenever i choose a value in dropdown, the textfield will show an output based on the selected value from the dropdown. But im always getting an error undefined variable from ff.php. I tried to pin down the cause, and what i found is im not getting any POST value in ff.php. Any solution for this ? Thanks in advance.
Here is my code in prs.php
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:'productid='+val,
success: function(data){
$("#brandss").val(data);
}
});
}
</script>
<td><select name="drpcode" onchange="getState(this.value)" class="form-control name_list"><?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?></option><?php } ?></select></td>
<td><input type="text" id="brandss" name="brand" placeholder="Brand" class="form-control name_list" required value=""></td>
Here my codes in ff.php
<?php
require_once("conn.php");
$id = $_POST['productid'];
$query = mysqli_query($conn,"SELECT productbrand FROM products WHERE productid = '$id' ");
while($rs = mysqli_fetch_array($query,MYSQLI_BOTH)) {
$brand = $rs['productbrand'];
}
echo $brand;
?>
Please add the data in json format and specify the datatype as json in ajax function
$.ajax({
url: "ff.php",
type: "POST",
data: {
productid : val
// more fields can be added here
},
dataType: 'json',
success: function(return){
// process success
},
error: function(err) {
// Process failure
}
});
I think the format of ajax data attribute is wrong . You should try this :
data:{productid:val}
UPDATE :
you should select both productid and product code in select statement
<td>
<select name="drpcode" onchange="getState(this.value)" class="form-control
name_list">
<?php $drp = mysqli_query($conn,"SELECT productid,productcode FROM
products");
while ($dp = mysqli_fetch_array($drp)) {
?><option value="<?php echo $dp['productid']; ?>"><?php echo
$dp['productcode']; ?></option><?php } ?>
</select>
</td>
function getState(val) {
$.ajax({
type: "POST",
url: "ff.php",
data:{productid:val},
success: function(data){
$("#brandss").val(data);
}
});
}
Try running the query before select and then display result with loop-
<?php $drp = mysqli_query($conn,"SELECT productcode FROM products"); ?>
<select name="drpcode" onchange="getState(this.value)" class="form-control name_list">
<?php while ($dp = mysqli_fetch_array($drp)) { ?>
<option value="<?php echo $dp['productid']; ?>"><?php echo $dp['productcode']; ?>
</option><?php } ?>
</select>

how to post data with ajax, php and bootstrap select

I am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through
Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});

Changing the values on second <select> tag after changing the first <select>

The title says my goal here. I'm trying to change the second select tag's values on change of the first tag. Here is what I've tried. The values are coming from the database. So this will involve some php selects.
<div class="row">
<div class="col-md-5">
<label for="project">From Project</label>
<select class="form-control"id="project"onchange="dropDrown(this.value)" name="project">
<?php
$sql = $db->prepare("SELECT * FROM tbl_project WHERE projectStatus = 1");
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_ASSOC)){
$value = $result['projectID'];
$projectName = $result['projectName'];
echo"
<option value='$value'> $projectName </option>
";
}
?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-5">
<select class="form-control" id="village" name="village"></select>
</div>
</div>
The AJAX:
<script type="text/javascript">
function dropDown(id){
var theID = id;
// assign your data to a varaible
var dataString= {theID:id};
$.ajax({
url: "includes/getVillage.php",
type: "POST",
data: dataString,
cache: false,
success: function (data){
$("#village").html(data);
}
});
}
getVillage.php
<?php
include '../../connection';
$village = $_POST['theID'];
$sql = "SELECT * FROM tbl_village WHERE projectID = '$village'";
$query = $db->prepare($sql);
$results = $query->execute();
while($results=$sql->fetch(PDO::FETCH_ASSOC)){
$value = $results['villageID'];
$text = $results['villageName'];
echo "<option value'$value'>$text</option>";
}
It seems you are not passing data through your ajax call.
function dropDown(id){
var theID = id;
// assign your data to a varaible
var dataString= {theID:id};
$.ajax({
url: "includes/getVillage.php",
type: "POST",
data: dataString,
cache: false,
success: function (data){
$("#village").html(data);
}
});
}
Alternatively you can pass the values in the below format
var dataString= "theID="+id;
It turns out that I made a wrong connection. After evaluating the getVillage.php file alone. I received a lot of errors regarding my connection.php. Thanks guys.

How to display all checkboxes values in a div using ajax

I have multiple checkboxes displayed from MySQL table. I'm trying to pass all checked values to <div> using ajax. Currently, my code only passes one checked value to <div>. I want to display all checked values in a <div>.
What I have thus far:
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
ajax
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML =data;
}
});
}
</script>
ajax_price.php
<?php
include ("../supplier/DB/db.php");
$id = $_REQUEST['option'];
<?php
$sql="SELECT * FROM options WHERE op_id='".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<div class="oder">
<div class="odercol2"><?php echo $row['opt']; ?></div>
<div class="odercol3"><?php echo $row['price']; ?></div>
</div>
<?php
}
?>
This is the display with only one checked value in the <div>. I want to display all the checked values in my <div>.
checkboxes
Results display in this div (div id is "c")
Just change your AJAX function to concat the innerHTML of DIV, like this:
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML += data;
}
});
}
</script>
Notice this line document.getElementById('c').innerHTML += data;
Hope it works. Thanks
Add a class value in the checkbox
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" class="sundarCheckBox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
Loop using the class name input elements
<script>
$(document).ready(function(){
function showPrice(value){
$.each($('.sundarCheckBox'), function(index, element){
if($(element).is(':checked')){
alert($(element).prop('value'));
}
});
}
});
</script>

selected item in query fro dropdown list in php

Here is my code I made a script to get values in "list_cust_city" from selected item in "list_cust_name" through query in php. I didnt get any values in "list_cust_city" for city. I made city.php.
<script>
$('#list_cust_name').change(function(){
alert("heyyy");
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
</script>
<label style="color:#000">Name </label>
<?php
$query_name = "SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name"; //Write a query
$data_name = mysql_query($query_name); //Execute the query
?>
<select id="list_cust_name" name="list_cust_name">
<?php
while($fetch_options_name = mysql_fetch_assoc($data_name)) { //Loop all the options retrieved from the query
$customer=$fetch_options_name['cust_name'];
?>
<option value="<?php echo $fetch_options_name['cust_name']; ?>"><?php echo $fetch_options_name['cust_name']; ?></option>
<?php
}
?>
</select>
city.php
<body>
<?php
include('dbconnect.php');
db_connect();
$cust_name1=$_GET['cust_name']; //passed value of cust_name
$query_city = "SELECT DISTINCT cust_city FROM customer_db WHERE cust_name='$cust_name1'ORDER BY cust_city"; //Write a query
$data_city = mysql_query($query_city); //Execute the query
while($fetch_options_city = mysql_fetch_assoc($data_city)) { //Loop all the options retrieved from the query
?>
<option value="<?php echo $fetch_options_city['cust_city']; ?>"><?php echo $fetch_options_city['cust_city']; ?></option>
<?php
}
?>
</body>
You must use document ready because the DOM isn't load.
$( document ).ready(function() {
$('#list_cust_name').change(function(){
alert("heyyy");
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
PHP uses . to concat strings. Change your query to:
$query_city = 'SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'"ORDER BY cust_city';
Also add this to your first php file:
<select id="list_cust_city" name="list_cust_city"></select>
Here's full code.
php 1:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
$('#list_cust_name').change(function(){
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
</script>
<label style="color:#000">Name </label>
<?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name");?>
<select id="list_cust_name" name="list_cust_name">
<?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?>
<option value="<?php=$fetch_options_name['cust_name']; ?>"><?php=$fetch_options_name['cust_name']; ?></option>
<?php } ?>
</select>
<select id="list_cust_city" name="list_cust_city"></select>
city.php:
<?php
include('dbconnect.php');
db_connect();
$cust_name1=$_GET['cust_name'];
$data_city = mysql_query('SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'" ORDER BY cust_city');
while($fetch_options_city = mysql_fetch_assoc($data_city)) {
?>
<option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
<?php
}
?>

Categories