Im using TomSelect to control my <select> UI for my dependent select dropdowns.
The <option>...</option> list of the To dropdown depends on the From dropdown and is updated per ajax call on the selection in the From dropdown. The first initialization works fine on both dropdowns. Unfortunately, after repeating the ajax request through selecting another location on the From dropdown results in the following error:
Uncaught Error: Tom Select already initialized on this element
What i did so far:
1. On page load i'm initializing TomSelect on the From dropdown with:
tsfrom = new TomSelect('#from-select-field',ttddssettings);
The relevant lines of code:
<select id="from-select-field" name="from" onchange="getTo();">
<option value='0'>Choose...</option>
</select>
<select id="to-select-field" name="from">
<option value='0'>Select From first</option>
</select>
<script>
jQuery(document).ready(function($) {
var tsfrom;
var ttddssettings = {
plugins: ['dropdown_input'],
};
tsfrom = new TomSelect('#from-select-field',ttddssettings);
var totoval = "xymydomain.com/get-to-options.php";
getTo = function () {
var fromvalue = $("#from-select-field").val();
var tovalue = $("#to-select-field").val();
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
},
});
}
});
</script>
The relevant lines of code inside the requested PHP file:
<?php
$sql_to = "SELECT * FROM locations WHERE ..... ORDER by names ASC";
$quer_to = $pdo_conn->prepare($sql_to);
$quer_to->execute();
$fetch_to_values = $quer_to->fetchAll();
foreach ( $fetch_to_values as $tovalues ) {
?>
<option value="<?php echo $tovalue['name']; ?>" <?php if ( $tovalue['name'] == $to) { echo "selected";} ?>><?php echo $tovalue['name']; ?></option>
<?php } ?>
<script>
jQuery(document).ready(function($) {
var tsto;
var tttossettings = {
plugins: ['dropdown_input'],
};
tsto = new TomSelect('#to-select-field',tttossettings);
});
</script>
2. After selcting a From location the To dropdown gets populated per ajax. The requested file (see above) through ajax url: includes also the following code to initialize TomSelect on the To dropdown:
tsto = new TomSelect('#to-select-field',tttossettings);
So far everything works fine.
3. THE PROBLEM:
As mentioned before, after repeatedly selecting a different location on the From dropdown i get the error Tom Select already initialized on this element.
The TomSelect DOCS mentioning refreshOptions(triggerDropdown) (Refreshes the list of available options shown in the autocomplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.
Two changes should get rid of the error:
Remove script block from PHP page:
Get rid of the <script> block in your PHP file and only return the <option>...</option> values. This is also messy as you are setting the HTML of the <select> to be what the PHP code has generated, including the returned script block.
Trigger updating the drop down in the AJAX success block
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
tsto.clear(); // unselect previously selected elements
tsto.clearOptions(); // remove existing options
tsto.sync(); // synchronise with the underlying SELECT
},
});
Using the sync method should update the styled dropdown options based on the underlying <select>.
Alternatively, calling tsfrom.refreshOptions(); instead of sync() could also work.
Related
I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});
i have a select2 element that load data from database using ajax. i want to load the value from db and select it as selected value in edit mode.
but im not able to load the value using trigger function.
i tried using looping by comparing selected values but i got the select2 option orinted twice.
$(document).ready(function(){
var area = $('#area').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true,
allowClear: true,
width: 'resolve'
});
var k;
var selected = [];
//imloading the value from db and insert it into an array
<?php foreach($area_coll as $area){
?>
selected.push("<?php echo $area->group_branch_id;?>");
<?php
}?>
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
//looping cabang
for(j=0; j<data.length; j++){
$('#area').append($('<option>').val(data[j].GroupBranchID).text(data[j].branch));
}
}
});
//this function not working at all
area.val(selected).trigger("change");
});
im not getting any error with this code nor the value still not selected.
Select2 have ajax options.
So I think you can use ajax directly as an options of select2 (reference: https://select2.org/data-sources/ajax#default-pre-selected-values)
The document said:
To provide default selections, you may include an <option> for each selection that contains the value and text that should be displayed:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Mean that at the options you can push selected="selected" at edit page when option is stored on exist record.
Hope it help. thanks
I currently have a webpage that works great. I select my load number and a ajax query gets the information and puts the results in textboxs. The page is split, one part displays information, but when "print" is selected, it formats the results to print a bubble sheet.
Here is the problem. Instead of displaying the "On Screen" results in textboxs, I would rather just display as normal text.
The active page is located at this address
The retrieval code is quite long, here is a sample.
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#loads").change(function(){ /* TRIGGER THIS WHEN USER HAS SELECTED DATA FROM THE SELECT FIELD */
var loadnumber = $(this).val(); /* STORE THE SELECTED LOAD NUMBER TO THIS VARIABLE */
$.ajax({ /* START AJAX */
type: "POST", /* METHOD TO USE TO PASS THE DATA */
url: "actionprt.php", /* THE FILE WHERE WE WILL PASS THE DATA */
data: {"loadnumber": loadnumber}, /* THE DATA WE WILL PASS TO action.php */
dataType: 'json', /* DATA TYPE THAT WILL BE RETURNED FROM action.php */
success: function(result){
/* PUT CORRESPONDING RETURNED DATA FROM action.php TO THESE TEXTBOXES */
for (i = 1; i < 14; i++) {
$("#prtDescription" + i).val("");
$("#prtMethod" + i).val("");
$("#prtPONumber" + i).val("");
$("#prtGallons" + i).val("");
$("#prtAmount" + i).val("");
}
$("#NumberStops").val(result.NumberStops);
$("#ShipperName").val(result.CustomerName);
$("#prtship").val(result.CustomerName);
$("#ShipperAddr1").val(result.CustomerAddress);
$("#ShipperAddr2").val(result.CustomerAddress2);
$("#ShipperCity").val(result.CustomerCity);
$("#prtshipcity").val(result.CustomerCity);
$("#ShipperState").val(result.CustomerState);
$("#prtshipstate").val(result.CustomerState);
$Phone = result.CustomerPhone
$Phone = '(' + $Phone.substring(0,3) + ') ' + $Phone.substring(3,6) + '-' + $Phone.substring(6,10)
$("#ShipperPhone").val(result.CustomerPhone);
$("#ShipperContact").val(result.CustomerContact);
$("#PickupDate").val(result.PickupDate);
$("#prtdate").val(result.PickupDate);
$("#PickupTime").val(result.PickupTime);
$("#CustomerPO").val(result.CustomerPO);
$("#Weight").val(result.Weight);
$("#prtweight").val(result.Weight);
$("#Pieces").val(result.Pieces);
$("#prtpieces").val(result.Pieces);
$("#BLNumber").val(result.BLNumber);
$("#prtbol").val(result.BLNumber);
$("#TrailerNumber").val(result.TrailerNumber);
$("#prttrailer").val(result.TrailerNumber);
...
I tried document.write() but that cleared the page which is not what I am looking for. I want to keep my images and combobox selection box on the page so I can select other loads when needed rather then just one at a time.
Please help.... If you require more information to answer the question, please ask and I will post.
Why not just make a new div after your load selection and simply append all those results into it?
There are different options to use Ajax as per your Requirement. You can replace the Entire div with the new Data or with the Entire HTML or you can change the selected part alone. It is up-to you who have to choose the suitable method which will be easy for you.
These are the methods available:
Method 1:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(data) {
handleData(data);
}
});
}
This above method will replace the Ajax success with the data that is available after your process is completed.
Method 2:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(html) {
handleData(html);
}
});
}
The above function will replace the entire success div with the new HTML part.
Now i will illustrate it with a simple example of how to replace the div using PHP and HTML using AJAX.
Scenario: User Has to select the city and the City Details will load up in Ajax.
HTML:
<select name="city" onchange="selectcity(this.value)">
<option value="">Please Select</option>
<option value="1">USA</option>
<option value="2">Europe</option>
</select>
<div id="ajax_output">
</div>
While selecting the city it will load up the function by using onchange attribute in jQuery and the Ajax will be passed.
JS:
function selectcity(a) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&city="+a,
success:function(html) {
$('#ajax_output').html(html);
}
});
}
In the JS am getting the selected value using a since i have passed a parameter to the function and passing it to the Ajax Page.
Ajax Page:
Note: Ensure that if you are going to display the information form the DB you have to connect the DB file to the Ajax page.
<?php
$city_id = $_POST['city']; // Jquery Data that i am retriving on Ajax Page
$select="SELECT * FROM TABLENAME WHERE `city_id`='".$city_id."'";
$query = $con->query($select);
$count = $query->num_rows;
if($count==0)
{
echo 'No Data Found';
}
else
{
while($fetch = $query->fetch_assoc())
{
?>
<div class="col-sm-6">
<label>City</label>
<span><?php echo $fetch['city_name']; ?></span>
</div>
<div class="col-sm-6">
<label>Place</label>
<span><?php echo $fetch['place']; ?></span>
</div>
<?php
}
}
?>
Now in my example i am going to replace the #ajax_output div with the content that is going to come from the Ajax page.
As per the request made in the question i hope so this would be the easiest method so that PHP will execute faster when compared to the JS and the Errors will also be minimal when you use this method.
Hope so my explanations would be clear for you and if you face any hindrance in development let me share thoughts and i will provide you with a solution.
Happy Coding :)
I have a page which displays All Test Events on default (Initial Page View)
My controller:
public function testController()
{
$category = 0; //NEED TO BE CHANGED WHEN USER SELECTED TEST EVENT 2 AND GET ALL EVENTS (Category 2)
$getEventsBasedOnCategory = //DB QUERY TO GET ALL EVENTS (Category 0)
//Pass all events to view
}
My HTML page:
<select id = "event_filter">
<option value="" selected="selected" disabled>SELECT Event</option>
<option value="0">All Test Events</option>
<option value="2">Test Event 2</option>
</select>
My ajax request:
$("#event_filter").change(function(){
$.ajax({
url: '/site/example/displayEvents',
data: {
event_filter: $("#event_filter").val()
},
async: false,
type: 'POST',
success: function(data){
},
});
});
My question is how am I going to change the category to 2 (if user selected 2 in select box) and request again from the database and display the events with category 2 on site?
Im using codeigniter by the way. Thanks
Thanks, Sorry for bothering you guys.
Sorry for my bad English.
First of all, to retrieve data from post in codeigniter use $this->input->post('event_filter').
If you are calling '/site/example/displayEvents', in this function "displayEvents" you have to call the function in the model.
public function displayEvents(){
$data->variableToSend = $this->example_model->events_data($this->input->post('event_filter'));
$this->load->view('nameOfViewToDisplayData',$data);
}
The view is the result in your ajax call, then you can put it in a div.
success: function(data){
$('#target_div').html(data);
},
When you're using type: POST, this will post it to the next site :-)
The way i understand your question, you need the $category to be equal to the value of your select.
I havent testet you script, but they way you do it:
$category = 0;
if(isset($_POST['event_filter'])){
$category = $_POST['event_filter'];
}
and then just a simple
"SELECT * FROM {your category} WHERE {your_row_category} = $categori"
When I select one item from 1st dropdown, an ajax event will fire up, invoke another function that will and load information to the second dropdown. I do not want this (No button solution please)
<select id=combo1>
<option>...</option>
...
</select>
<input type=button onclick="loadCombo2()">
You can go about something like this:
<select id="combo1" onchange="requestSend(this.value);">
options..........
</select>
<select id="combo2">
options...........
</select>
<script>
function requestSend(txt)
{
$.ajax({
url:'process.jsp',
data: "v=" + txt,
cache:false,
success: function(response){
$("#combo2").val(response);
}
});
}
</script>
....
Populating Combo2 Options:
To populate combo2 options, you need to create them in the script which process ajax request, for example in php (i don't know which language you are using), i will do something like this in ajax processing script:
// db queries to get data or whatever
// create a variable that will hold options and shown in combo2
$options = '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
//........ etc
// Now we send back the $options variable which will populate the combo2
echo $options;
If it was being implemented in ASP.NET I'd use an HTTP handler to return the data in JSON format to the second combobox.
Using jQuery you'd call the handler in the following way to implement cascading:
$("#combo1").change(function()
{
$("#combo2").html("");
var valueSelected = $("#combo1").val();
if (valueSelected != 0)
{
$.getJSON('LoadCombo2.ashx?valueSelected=' + valueSelected, function(returnedData)
{
$.each(returnedData, function()
{
$("#combo2").append($("<option></option>").val(this['ID']).html(this['Value']));
});
});
}
});
To see how to implement the HTTP handler, take a look at a more complete step-by-step in this post:
http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx
If you don't need cascading the comboboxes, it gets easier. Just call the handler passing no parameters and load any data you need to fill the second combobox in the callback function of jQuery.
http://api.jquery.com/jQuery.getJSON/
Hope you get the idea.