I created an admin panel for MySQL database, and when I click on the edit button, I want to print all of the datas in Bootstrap multi select. If I didn't use Bootstrap multi select, just the normal multi select, it's working. How can I do this?
This is how it looks like (in the button, it show the current datas, but when I open, it didn't showin the select menu):
index.php
<select name="classification[]" id="classification" multiple="multiple">
<?php
while($row = $classificationResult -> fetch_array()) {
?>
<option value="<?php echo $row['classification_id'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
<script>
// If I didn't add the multi select jquery, it's working
$('#classification').multiselect({
nonSelectedText: 'Select Framework',
maxHeight : 400,
includeSelectAllOption : false,
enableFiltering : false,
buttonWidth : '100%',
dropRight : true
});
$(document).on('click', '.edit_data', function(){
$("#classification option").prop("selected", false);
var data_id = $(this).attr("id");
$.ajax({
url:"fetchRole.php",
method:"POST",
data:{'data_id':data_id},
dataType:"json",
success:function(data){
$.each(data.classifications, function(i, e) {
$("#classification option[value='" + e + "']").prop("selected", true);
});
$('#data_id').val(data.id);
$('#insert').val("Edit");
$('#add_data_Modal').modal('show');
}
});
});
</script>
fetchRole.php
$query2 = $conn -> prepare("SELECT classification.classification_id AS class_id
FROM classification
LEFT JOIN role_classification ON classification.classification_id = role_classification.classification_id
WHERE role_classification.role_id = ?");
$query2 -> bind_param('i', $role['id']);
$query2 -> execute();
$result2 = $query2 -> get_result();
$query2 -> close();
while ($classification = $result2 -> fetch_assoc()) {
$classificationIdList[] = $classification["class_id"];
}
$return = array_merge($role, ["classifications" => $classificationIdList]);
echo json_encode($return);
You need to refresh the multiselect after you set new selected options using .prop("selected", true).
$.each(data.classifications, function(i, e) {
$("#classification option[value='" + e + "']").prop("selected", true);
});
$('#classification').multiselect('refresh');
Description of the refresh method:
This method is used to refresh the checked checkboxes based on the
currently selected options within the select.
You can see the full list of available methods HERE.
Related
EDIT 1 - BRIEF
This is how it is. https://ibb.co/9WY5gLL it has a datatable, which is sorted according to dropdown selections and there is a button to reset the sortings. the reset part is working fine except the text in dropdown is not changing. but if I remove the slect box class in dropdown HTML all working fine.
//DROPDOWN HTML
<select name="status" id="status" class="statusbox SlectBox form-control">
<?php echo loadStatus(); ?>
</select>
//DATATABLE
$(document).ready(function() {
var table= $('#tableone').DataTable( {
"serverSide": true,
"ajax": {
url :"sonme.php",
type : "POST",
data : function(data){
var status = $('#status').val();
data.status= status;
}
} );
} );
//TABLE FILTER
$('#status').change(function(){
table.draw();
});
//RESET TABLE
$('#reset').click(function() {
$("select.statusbox").val($("select.statusbox option:first").val()).change();
});
//PHP RETURNED BY AJAX CALL
function location(){
global $con;
$output.= '<option value="_allCity">All Results</option>';
$_selectquery= "SELECT * FROM _tableone";
$result = mysqli_query($con, $_selectquery);
while($row = mysqli_fetch_array($result)){
$output.= '<option value = "'.$row["name"].'">'.$row["name"].'</option>';
}
return $output;
}
Since this is the sumo select jquery plugin, all what I had to is reviewing the documentation.
This line - $('select.SlectBox')[0].sumo.reload(); reset the dropdown and value as the default. Please check the doc: https://hemantnegi.github.io/jquery.sumoselect/
I have created a website. I have created a dropdown in it for displaying different data while the user selects different dropdown, my code is as below
$(document).ready(function(){
// code to get all records from table via select box
$("#course_title").change(function() {
var tid = $(this).find(":selected").val();
var dataString = 'tid='+ tid;
$.ajax({
url: 'mycourses.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
if(employeeData) {
$("#heading").show();
$("#no_records").hide();
$("#emp_name").text(employeeData.tid);
$("#emp_age").text(employeeData.training_name);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
<select class="form-control sel" name="trainings" id="trainings" >
<option value="select options" selected disabled>Select Training Course</option>
<? $sql_trainings = "SELECT * FROM tbl_data";
$trainings_data = mysqli_query($con,$sql_trainings);
while($row = mysqli_fetch_assoc($trainings_data) ){
$trainingid = $row['tid'];
$training_name = $row['training_name'];
echo "<option value='".$trainingid."' >".$training_name."</option>";
}
?>
</select>
i have another page as getcourses.php as below
<?php
include "config.php";
$trainingid = $_POST['tid']; // department id
$sql = "SELECT tid,training_name FROM tbl_data WHERE id=".$departid;
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ){
$userid = $row['tid'];
$name = $row['training_name'];
$users_arr[] = array("tid" => $userid, "training_name" => $name);
}
// encoding array to json format
echo json_encode($users_arr);
The dropdown is first displayed in a page, then when the user clicks the dropdown, they are taken to different page showing the content of the dropdown they selected, it's showing the content the first time when the user clicks the dropdown and is being taken to the different page to show content, but when the user clicks different dropdown from the result page the dropdown doesn't work, nothing happens, I want to display the content of dropdown which the user selects in the resulting page, whenever user changes dropdown it should be appearing. my table name is tbl_data and my columns are tid and training_name.
Can anyone tell me what is wrong with my code?
$("#course_title").change(function() {
should be,
$("#trainings").change(function() {
So your js code should be like,
$(document).ready(function() {
// code to get all records from table via select box
$("#trainings").change(function() {
var tid = $(this).val(); // this is enough to get selected value
$.ajax({
url: 'mycourses.php',
type: 'POST', // you forgot type
data: {tid : tid},
success: function(employeeData) {
// same as your code
}
});
})
});
I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>
I have the following code:
<select name="trec">
<? $d -> gettreatment(); ?>
</select>
<select name="treratment">
<? $d -> gettreat(); ?>
</select>
the <? $d -> gettreatment(); ?>
will display echo "<option value='$r[id]'>$r[cat]</option>";
and <? $d -> gettreat(); ?>
will display echo "<option value='$r[id]'>$r[treatment]</option>";
How to dynamically narrow down (or limit) the items in a second drop down list based on the selected item from first selected item? For example if we have one list of countries in first drop down list and have list of states in the second list then once USA is selected from the country list then the second list should change to list only the states of USA
<script type="text/javascript">
$(function() {
$("#form_process").click(function() {
//$("#choice").val(); //you cannot use the same id for more than 1 tag
var choice = 0;
if(document.getElementById("choice1").checked) choice='Yes';
else if(document.getElementById("choice2").checked) choice='No';
else if(document.getElementById("choice3").checked) choice='Dont Know';
var comments = document.getElementById('comments').value; //$("#comments").val();
var dataString = 'choice='+ choice + '&comments=' + comments;
$.ajax({
type: "POST",
url: "**ABSOLUTE URL TO PROCESSOR**",
data: dataString
});
});
});
</script>
Please look at this code first:
$(document).ready(function() {
$("#alternatecolor [type=button]").each(function() {
$(this).on('click', function() {
btnObj = $(this);
rowId = $(this).attr("rowId");
changeStatus = $(this).attr("changeStatus");
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(changeStatus == 0){
str ="Unverify";
btnText = "Verify";
newStatus = 1;
}
else{
str ="Verify";
btnText = "Unverify";
newStatus = 0;
}
if(data == 'success'){
alert("Status updated successfully to "+str+".");
btnObj.val(btnText);
btnObj.attr("changeStatus",newStatus);
}
else{
alert("some error");
}
});
});
});
});
</script>
Here is my change status page:
$dbhost = 'xxxxxx';
$dbuser = 'xxxxxxx';
$dbpass = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('xxxxxxxx');
$sql ="update experiment set verification=".$_GET['changeStatus']." where row=".$_GET['rowId'];
$retval = mysql_query( $sql, $conn );
if(!($retval))
{
die('error');
}
else{
echo "success";
}
mysql_close($conn);
I was using a button in this code to query my database with values 0,1. If pressed once, database queried with 1, if pressed again, database queried with 0.
Now, I have to put a dropdown in place of button with 3 values to query database with: 0,1,2. If selected first value, database row to be updated with value 0 and so on.
How would I do that?
remove button and add select like this:
<select class="my-select">
<option value="0">update</option>
<option value="1">create</option>
<option value="2">delete</option>
</select>
you also need to add data-rowId attribute.
jquery:
$(document).ready(function() {
$(".my-select").change(function() {
btnObj = $(this);
rowId = $(this).attr("data-rowId");
changeStatus = $(this).val();
$.get("changeStatus.php?rowId="+rowId+"&changeStatus="+changeStatus,function(data,status){
if(data == 'success'){
alert("Status updated successfully to "+str+".");
}
else{
alert("some error");
}
});
});
});
update
create
delete
You can do using class name or ID. If it's id then do $("#id1").click(function () {... in below code.
Awlad has done using GET method, below is using POST method.
$(function () {
$(".my-select").click(function () {
var category = $(this).text();
//$('label').css('color', selText);
$.ajax({
url: "invite_db.php",
type: "POST",
data: {"category": category},
success: function(data) {
$(".articleContent").html(data);
//setInterval("messageDisable()", 5000);
}
});
});
});
I have used parameter name according to my code. Please you change it
Here is your HTML and Javascript code
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<script type="text/javascript">
function getval(sel) {
$.ajax({
type: "POST",
url: url, // url is page where you want to process this post request
data: 'val=' + sel.value,
});
}
</script>
On PHP side
<?php
// Your database connection code
$val = $_POST['val'];
mysql_query("UPDATE 'tablename' SET 'column name' = $val 'Your WHere caluse'")
?>