This question already has answers here:
select2 jquery plugin not working after ajax calling for HTML content change
(2 answers)
Closed 3 years ago.
I have one initial dropdown, where I want to select a value:
<select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;">
<option value='' selected>Select and Index</option>
<option value='3'>AIM</option>
<option value='1'>FTSE 100</option>
<option value='2'>FTSE 250</option>
</select>
When a different value is selected it runs the updateSector() function, which uses an ajax script to load all the sectors which are relevant for the selected category. The output from the page investment_sectors is then displayed in a tag on the page.
function updateSector(){
<? if ($sectorID<>""){?>
var sectorID = <?=$sectorID?>;
<? }else{?>
var sectorID = "";
<?}?>
var indexID = document.getElementById("indexID");
var indexID = indexID.options[indexID.selectedIndex].value;
var dataString = 'indexID=' + indexID +'§orID=' + sectorID;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
}
});
}
This all works if I want to generate a standard select dropdown of the sectors. But as there are many sectors, I really want a select2 field.
Normally, if I was just including the select2 field in a standard page, I'd add this script to the bottom to load any passing values I want preselected. However, as the tag is empty until an option is selected and passed back, there is nothing to populate.
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
$(document).ready(function() {
var select2single = $('.js-example-basic-single').select2({
placeholder: "Please Select",
width: '400px',
multiple: false,
})
select2single.val([<?=$sectorID?>]);
select2single.trigger("change");
});
</script>
Can anyone help me adapt my code to generate this select2 field, rather than a standard select dropdown?
Thanks
This is the code in the called investment_sector page:
$sectorID=$_REQUEST['sectorID'];
$indexID=$_REQUEST['indexID'];
switch ($indexID){
case "1":
$sectorlist = "FTSE";
break;
case "2":
$sectorlist = "FTSE";
break;
case "3":
$sectorlist = "AIM";
break;
default:
$sectorlist = "";
}
$query = "SELECT * FROM tbl_sector WHERE sectorlist='".$sectorlist."' order by sector ASC";
$result = mysqli_query( $conn, $query )or showError( mysqli_query( $conn, $query ) );
$num_rows = mysqli_num_rows( $result );
echo "<select class=\"js-example-basic-single js-states form-control\" id=\"sectorID\" name=\"sectorID\">";
if ($sectorID==""){
echo "<option value='' selected>Select a ".$sectorlist." sector</option> \n ";
}
$i = 0;
while ( $row = mysqli_fetch_array( $result ) ) {
if ( $sectorID == $row[ 'sectorID' ] ) {
echo "<option value='" . $row[ 'sectorID' ] . "' selected>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option> \n ";
} else {
echo "<option value='" . $row[ 'sectorID' ] . "'>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option>\n";
}
$i++;
}
echo "</select>";
The problem is that you only initialize select2 when your document is ready. For elements that are created in the DOM afterwards, it won't automatically happen, even if they have the same class. You should reinitalize select2 for the new elements when your ajax is completed. Try this:
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
$('#' + sectorID).select2();
}
});
Related
I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research
I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}
Good day to everyone. So I am trying to get the value of a select option and getting a set of rows in MySql depending on the column name in the database. So here is the HTML code:
<html>
<body>
<select name = "FilterDoc" onchange = "filterby(this);">
<option disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option>
</select>
<div class="panel-body" id="container">
</div>
Here is code for Ajax:
<script type="text/javascript">
function filterby(sel){
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {FilterDoc: $(sel).val()},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response)
{
$("#responsecontainer").html(response);
}
console.log(reply);
});} </script>
Now the value of the select option will pass to the PHP file. I dont know if "if statement" is the right one for this since I haven't had that much background about getting values on html and such and I'm trying to find a better way to get the rows from MySql and display them into the container.
Here's the PHP code:
<?php echo"<div class='panel panel-primary' id='container'>";
if($_POST["FilterDoc"]=="document_type")
{
echo "<script type='text/javascript'>$('container').html('""');</script>";
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="date")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY date_received DESC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="hei")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY hei ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Person")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY contact_person ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}echo"</div>"; ?>
I'm also not entirely sure if using javascript to clear the container is the proper way before putting contents into the div container.
I would really appreciate your help. Thank you!
At first i would simplify the code like :
<?php
echo "<div class='panel panel-primary' id='container'>";
// Set Variable
$filter = $_POST["FilterDoc"]; // This needs proper escaping
$result = mysqli_query($conn,"SELECT * FROM records ORDER BY $filter ASC");
while($data = json_encode(mysql_fetch_assoc($result)) {
echo json_encode($data);
}
echo "</div>";
Thats the PHP part, now i would rewrite the javascript.
function filterby(sel) {
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {
FilterDoc: $(sel).val()
},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#container").empty().html(response);
}
});
}
But maybe your whole filtering process may be inefficient. You could fetch all the data with one SQL call and do the filtering with JS / data-attributes.
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.
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);