How to add a <select> <option> with jquery dynamically? - javascript

Changed value of <select> on success response from API with:
jQuery('#vat').val(response);
With this returned value can be placed into a textbox, but need to change the selected value of a combobox.
How to realize this?
Here is jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
console.log("getPrice after ajax", jQuery('#product_name').val());
jQuery('#vat').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script works when #vat is a textbox but not when #vat is a combobox.
Update:
Here is the script been using for the combobox:
<?php
$dbname = 'db';
$dbuser = 'root';
$dbpass = 'pass';
$db = new mysqli('localhost', $dbuser, $dbpass, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<select style="width:100%" id="vat" name="vat">
<option value = "0">No VAT</option>
<?php
$queryusers = "SELECT id, internal_id, name FROM vat";
$db = mysqli_query($db, $queryusers);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='".$d['id']."'>".$d['internal_id']." | ".$d['name']."</option>";
}
?>
</select>
Update 2:
The selected value is changed to '1'. But the script still shows <option value = "0">No VAT</option>. Does someone know how I can update the data that is shown.
Update 3:
I just get a extra option when I run the following script. The value that is represented as the selected value is still the same:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
// and put the price in text field
var newOption = "<option value=" + response + ">" + response + "</option>";
$("#vat").append(newOption);
$("#vat").val(response);
getPrice();
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>

You are right <select> value will be changed with $("#vat").val(1). However this will not create a new <option>. If there would be an <option value="1"> then this option would have been shown. Since it doesn't exist thus HTML have nothing to show and showing default <option> of <select>.
You need to create a <option> and append it to <select>.
Here's jQuery on success:
var newOption = `<option value=` + response + `>` + response + `</option>`;
$("#vat").append(newOption);
$("#vat").val(response);

Related

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

AJAX/jQuery gives a mysterious integer

I am using the latest jQuery. When I request some data from the server, I get a mysterious number 5 for no reasons at all. I checked my PHP code and console logged it and this is the result.
5<option value="" disabled selected>Choose your grade level</option>
<option value="9">Grade 9 - Red Lions</option>
There should no number 5 in that log at all.
AJAX Request:
$.ajax({
url: 'fetch_levels.php',
type: 'post',
dataType: 'html',
data: {parent: $(this).val() },
success: function(data)
{
var data = data;
data.replace('5', '');
$('#level-list').html(data);
console.log(data);
}
});
PHP Code:
<?php
require '../assets/php/init.php';
if ($_POST)
{
$schoolID = Essentials::sanitize($_POST['parent']);
$fetchSQL = "SELECT `levelid`, `name` FROM `grade` WHERE schoolid = ?";
$fetch = $conn->prepare($fetchSQL);
$fetch->execute([$schoolID]);
$fetchRes = $fetch->fetchAll(PDO::FETCH_ASSOC);
if(!$fetchRes) {
echo '
<option value="" disabled selected>Unfortunately, there is no levels here.</option>
';
} else {
echo '<option value="" disabled selected>Choose your grade level</option>';
foreach ($fetchRes as $level)
{
echo '
<option value="'.$level['levelid'].'">'.$level['name'].'</option>
';
}
}
}
Tried Solutions:
I've tried adding var data = data; data.replace('5', '') and it still doesn't work.
UPDATE:
This is the init.php
<?php
# Configuration for the application
$GLOBALS['config'] = [
'registerAdmin' => true
];
# Start the Session
session_name('iLearn');
session_start();
# Include essentials files
include 'language.php';
# Autoregister Classes
spl_autoload_register(function($class){
require 'Classes/' . $class . '.class.php';
});
$conn = new PDO('mysql:host=localhost;dbname=iLearn', "astroxoom", "-");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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>

trouble in handling json response

I have two select box and want to populate 2nd select box based on onchange of first select box. so my code for first select box
<select id="category-box" name="category" onchange="showCrops()" >
<option value ="0">Select category</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
onchange function for ajax call
function showCrops() {
var name = $('#category-box').val();
$.ajax({
type: "POST",
url: "getCropName.php",
data: {category:name},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$.each(opts, function(i,d) {
$('#crop-box').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
php code to get response
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category = $_POST['category'];
$sql1 = $con->query("SELECT category_id from categories where category ='".$category."' ");
$row1= $sql1->fetch_array();
$sql2 = $con->query("SELECT * from crop_category where category_id ='".$row1['category_id']."' ");
while($row2 = $sql2->fetch_assoc()){
echo json_encode($row2);
}
json response is
{"crop_id":"1","category_id":"1","crop_name":"rice"} {"crop_id":"2","category_id":"1","crop_name":"wheat"}
but i'm getting 'parsererror' on main php page. Whats the problem in my code ? i have less knowledge in javascript so maybe need correction to populate by 2nd select box.
Just change the php code, so the right JSON string is generated ..
$arr = array();
while($row2 = $sql2->fetch_assoc()){
$arr[] = $row2;
}
echo json_encode($arr);

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