how to append json_encode data into drop down list - javascript

I have two input field. I want to get value of 1st input field and sent it to database to get value of 2nd input field through php query. right now i am getting data in alert but I don't know how to put the values in second drop down.
I am getting data in alert. but how i can show data in #second-dropdown select tag.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
alert(data);
}
})
})
});
</script>
<select id="first-dropdown">
<option value="0">Select Product Line</option>
<option value="1">Living</option>
<option value="2">Kitchen</option>
<option value="3s">Bathe & Utility</option>
<option value="4">Furniture</option>
</select>
<select id="second-dropdown">
</select>
and my getUrl file is :
<?php
$id = $_GET['id'];
$query = mysql_query("select category_name from product_categories where Line_Code='$id'");
while($data = mysql_fetch_assoc($query)){
$values[] = array(
'product_categories'=>$data['category_name'],
);
}
echo json_encode($values);
?>
I want to show data in #second-dropdown. any one give me solution i am trying this since six hours.

this is for parsing your data in json
var new_data = $.parseJSON(data);
or add/edit your ajax property
datatype:"json"
Try this in your success function.
$("#second-dropdown").html('');
//var new_data = $.parseJSON(data);
$.each(new_data, function (i, item) {
$('#second-dropdown').append($('<option>', {
value: item.product_categories,
text : item.product_categories
}));
});

Here is one more way to do this (without json):
<?php
$id = $_GET['id'];
$query = mysql_query("select category_name from product_categories where Line_Code='$id'");
$retval="";
while($data = mysql_fetch_assoc($query)){
$retval=$retval."<option value='".$data['category_name']."'>".$data['category_name']."</option>";
}
echo $retval;
?>
and in your script:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
$("#second-dropdown").html(data);
}
})
})
});
</script>

$(document).ready(function(){
$("#first-dropdown").off("change").on("change", function(){
$.ajax({
'url':"getUrl.php",
'dataType':"json",
'data':{id:$("#first-dropdown").val()},
'method':'GET',
'success':function(data){
alert(data);
var results=data.d.results; //only assumption here this is a array of element with required option value. if it is not we need to print response data and check where all the value of options are stored.
var option='';
$("#second-dropdown").html('');
for(var i=0;i<results.length;i++)
{
option+='<option value="'+results[i]+'">'+results[i]+'</option>';
}
$("#second-dropdown").append(option);
}
})
})
});

Add this code in your success function to parse your JSON and create the options you want to add in your select element.
var options = JSON.parse(data);
for(var i in options){
$("#second-dropdown").append("<option value='"+ options[i].product_categories +"'>"+ options[i].product_categories +"</option>");
}
JSON.parse transform your JSON string as an array that you can manipulate with JavaScript.
The loop for create html options for the select then append these elements to the select.

Related

Can't print POST variable from AJAX using PHP

I am getting a list of data from a mysql database which I add to a select list. When the user chooses an option I want to get the ID from the selected item, and use it to reference the index of my results array, like this:
echo $results[$id]['fruit'];
I retrieved the data from the database using $results = $stmt->fetchAll(PDO::FETCH_UNIQUE) so each id of the select list is the primary key of the record.
So I read that I can use AJAX to get the value of the selected item and send it back as a POST variable which I can then access in PHP. However when I go to print this variable I get nothing.
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
Here is my code:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>
I think you may try this
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
var fruitTect = $(this).text(); // for text i.e. Apple, Pear,...
// then now you can do ur ajax
$.ajax({
// Your Code For Post goes here
});
});
});
No need to call the onchange function in your html. Jquery will take care of the rest
Also your isset($_POST['id']) maybe isset($_POST['fruits'])
Rogers answer is right. and you miss the url parameter in your ajax call.
function listChange() {
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
$.ajax({
url: '/myPhpFile.php',
method: 'POST',
data: {'id' : fruitValue},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
if you realy want to call it in a single file you have to place the php code in top and do an exit after the condition is fullfilled..
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
you need to encode as ajax expect a json data
$results_array = array("Id" => $id):
$json=json_encode( $results_array );
header('Content-Type: application/json'); //tell the broswer JSON is coming
echo $json; //Just plain vanillat JSON output
do your things here an exit. Be aware that each echo "something" falsify the json data expected by the ajax call
exit();
}
?>
Try use this code in HMTL.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange(obj) {
var recID = obj.value;
var recID = $("#fruits:selected").text();
$.ajax({
method: 'POST',
data: {'id' : recID},
url:'demo.php',(put url of php file and remove in this file make diffrent php file)
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange(this)">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>
Ok I found a much simpler way of doing this. Just get Javascript to encode the value in the URL when the select is changed, then access it in PHP using GET.
Encoding the URL in Javascript:
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="ajax.php?id=" + fruitValue;
});
});
</script>
Echo the value in PHP:
if(isset($_GET['id']))
{
$id = $_GET['id'];
echo $id;
}
Print data via the different file.
Php return data send to another file and ajax response data print in html.
Action file
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
View file
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url: 'action.php',
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
$('#your_id').html(response);
}
});
}
OR
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$("#your_id").html(recID);
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<div id="your_id"></div>
</body>
</html>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url:'ajax.php'
method: 'POST',
data: {'id' : recID},
success: function(response)
{
console.log(response);
}
});
}
</script>
<?php
print_r($_POST);
?>

Load MySQL data without Refresh Webpage

I try to populate a select box based on the value of the another, by getting JSON data with jQuery from a PHP script that gets the data from a MySQL database.
This is my table :
I hope, if i select a different fruit from the first selection, it will change the available varieties in the second select.
According to my script, i'm not able to get corresponding available varieties into the second select, what wrong on my script.
<form>
Fruit:
<select name="name" id="fruitName">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>
<script>
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['variety']);
});
});
}
$(document).ready(function() {
populate();
$('#fruitName').change(function() {
populate();
});
});
</script>
and this is my varities.php script
$result = array();
$fruitName = $_GET['fruitName'];
$res=mysql_query("SELECT variety FROM fruit WHERE name = '$fruitName' ORDER BY variety");
while ($row=mysql_fetch_array($res)){
array_push($result, array('variety'=>$row['variety']));
}
echo json_encode(array('result'=>$result));
Please any suggestions?
Try the following function
function populate() {
$.getJSON('varities.php', {fruitName:$('#fruitName').val()}, function(data) {
var select = $('#fruitVariety');
var options = select.empty();//empty the select box
$.each(data.result, function(index, array) {//don't forget you have a result array
select.append('<option value="'+array.variety+'">'+array.variety+'</option>');//append the option elements
});
});
}
Make 2 separate tables,one for the fruits and another for the variety. Id of tbl_fruits will be a foreign key in tbl_variety.
1)First get all fruits and store the results in $fruits.
Therefore, first select will be like:
<select name="name" id="fruitName">
<?php foreach($fruits as $fruit): ?>
<option value="<?=$fruit['id']?>"><?=$fruit['name']?></option>;
<?php endforeach; ?>
</select>
Then you can populate the 2nd dropdown using ajax:
<select name="variety" id="fruitVariety">
</select>
<script>
var id=$('#fruitName').val();
$.ajax({ // first call will get the list as per the initial value of the fruit list when the page loads
url:"get_variety.php",
method:"POST",
data:{initial:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
$('#category').change(function(){
var id = $(this).val();
$.ajax({ // this will be triggered whenever you select a different value from the fruits list
url:"get-variety.php",
method:"POST",
data:{id:id},
dataType:"html",
success:function(data)
{
$('#fruitVariety').html(data);
}
});
</script>
And in get-variety.php:
Check if $_POST['initial'] or $_POST['id'] is set and fire query accordingly:
$initial=$_POST['initial'];
$results= After executing('SELECT * FROM tbl_variety WHERE fruit_id="'.$initial.'"');
foreach ($results as $result) {
echo '<option value="' . $result["id"] . '">'.$result["variety"].'</option>';
}
Similary, run the query for the other POST variable.

Using AJAX and PHP to change combobox choices

I've been trying and struggling all morning to get my combobox to update properly. Once a user selects and option in the first box I want to then populate a second box with options applicable to the first option chosen. I have written a separate php script to take in the option chosen and pull from the sql database the applicable return. This script works fine when run by itself but I cannot get it working within the javascript using AJAX
PHP:
<?php
$name=$_GET['name'];
// select box option tag
$selectBoxOption1 = '';
// connect mysql server
$con=mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mysql',$con);
$sql1 = "SELECT DISTINCT bike_type FROM bc_fit WHERE name='$name'";
$result1 = mysql_query($sql1);
// play with return result array
while($row = mysql_fetch_array($result1)){
$selectBoxOption1 .="<option value = '".$row['bike_type']."'>".$row['bike_type']."</option>";
}
// return options
echo $selectBoxOption1;
?>
Javascript (#nap2 is the current box and #nap 4 the next):
$("#nap2").change(function(event){
var selected = $(this).find('option:selected').text()
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
//need to get options based upon nap 2 choice by calling php script with selected and returning all unqiue bike under that name
var options4;
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: "name"=selected,
success: function(data) {
options4 = data;
}
});
$('#nap4').append($(options4));
});
You have a few issues in your jQuery:
<select id="nap2" class="napkeeComponent napkeeCombobox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="2">Three</option>
</select>
<select id="nap4" class="napkeeComponent napkeeCombobox" disabled>
</select>
<script>
$(document).ready(function() {
$("#nap2").change(function(event){
// You just get the value of selected input
// You don't need to find anything because you've already selected it
var selected = $(this).val();
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$.ajax({
type: "GET",
url: 'getbiketype.php',
// Your creation of the data object is incorrect
data: { name: selected },
success: function(data) {
console.log(data);
// Here just append the straight data
$('#nap4').append(data);
}
});
});
});
</script>

Ajax show Dynamic data of php in html drop down

I am trying to get the data from a database and populate then in a drop down in the code below.
I am unable to populate them as the data output says:
"undefined index: selectid" from php ma be the data is not passing from ajax or the php is unable to read.
HTML:
<select id="dynamicDropdown"></select>
JS:
var storedValue = localStorage.getItem("id");
$.ajax({
url : "DD.php",
data: {"storedValue":storedValue},
success : function(data){
alert(data);
console.log(data) // data should be an array that you have mentioned.
data.map(function(c){
$("#dynamicDropdown").append("<option value="+c.C_CO+">"+c.C_NAME1+"</option>");
});
}
});
};
PHP:
$mysqli=mysqli_connect('xxx','xxx','xxx','xxx');
$selectid = mysqli_real_escape_string($mysqli,trim($_POST['storedValue']));
$query112 ="SELECT * FROM dd_table WHERE id='$selectid'";
$result112 = mysqli_query($mysqli,$query112)or die(mysqli_error());
$num_row112 = mysqli_num_rows($result112);
while($row=mysqli_fetch_array($result112))
{
$response = array($row['dd_data'] );
echo json_encode($response);
}
I might be wrong but shouldn't you write it like this :
$query112 ="SELECT * FROM dd_table WHERE id='".$selectid."'"; ?
You don't need any jQuery for that:
Try this:
<select>
<?php
foreach(mysqli_fetch_array($result112) as $x){
echo "<option>". $x['dd_data']. "</option>";
}
?>
</select>

dynamically updating select boxes with php mysql jquery ajax

I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});

Categories