I am trying to populate Bootstrap multiselect , I used the following code
html
<form>
<tr>
<td><label>Code Planteur :</label></td>
<td> <input type="text" id="code_planteur" name="code_planteur" class="code_planteur"></td>
</tr>
<tr>
<td><label>Numero de Ticket :</label></td>
<td><select id="num_ticket" name="num_ticket" class="num_ticket">
<option value="0"> numero de ticket </option>
</select></td>
</tr>
</form>
and my php file ticket.php
<?php
require 'conn.php';
if($_POST['id'])
{
$id=$_POST['id'];
$req="select column from table where code_planteur='".$id."' ";
$req = $pdo->query($req);
$results = array();
while($row=$req->fetch())
{
$data=$row['column'];
echo "<option value=".$data.">".$data."</option>";
}
}
?>
my javascript
$(document).ready(function(){
$(".code_planteur").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ticket.php",
data: dataString,
cache: false,
success: function(html){
$(".num_ticket").html(html);
}
});
});});
how can i transforme my code to use with bootstrap multiselect
example https://jsfiddle.net/j086fkdf/
it work with this javascript
$(document).ready(function()
{
$(".code_planteur").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({type: "POST",
url: "ticket1.php",
data: dataString,
cache: false,
dataType: "json",
success: function(data)
{
$("#num_ticket").empty();
$.each(data, function (key, val) {
$("#num_ticket").append('<option value="' + val + '">' + val + '</option>');
});
$("#num_ticket").attr('multiple', 'multiple');
$("#num_ticket").multiselect();
}
}
);
}
);
});
and my ticket1.php
<?php
require "conn.php";
if($_POST['id']){
$id=$_POST['id'];
$req="select num_ticket from paiement where code_planteur='".$id."' ";
$req = $pdo->query($req);
while ($row=$req->fetch() ){
$resultat[] = $row['num_ticket'];
}
echo json_encode($resultat);
}
?>
Modify your form
<form>
<tr>
<td><label>Code Planteur :</label></td>
<td> <input type="text" id="code_planteur" name="code_planteur" class="code_planteur"></td>
</tr>
<tr>
<td><label>Numero de Ticket :</label></td>
<td>
<select id="num_ticket" name="num_ticket" class="num_ticket">
<option> numero de ticket </option>
</select>
</td>
</tr>
</form>
For your ticket.php, i suggest you to use prepare query for more security
if($_POST['id']){
$id=$_POST['id'];
$req="select num_ticket from paiement where code_planteur=:id";
$stmt=$pdo->prepare($req);
$stmt->bindValue(":id",$id);
$stmt->execute();
$retour = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($retour as $key => $value) {
echo "<option value = '".$value['num_ticket']."'>".$value['num_ticket']."</option>\n";
}
}
And the ajax query
$(function(){
$("#code_planteur").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({type: "POST",
url: "ticket1.php",
data: dataString,
cache: false,
dataType: "json",
success: function(data)
{
$("#num_ticket").empty();
$("#num_ticket").html(data);
});
$("#num_ticket").attr('multiple', 'multiple');
$("#num_ticket").multiselect();
}
}
);
}
);
});
If you want the value to be populated as selected then just write the selected tag with option.
For more details please refer:http://www.jqueryscript.net/demo/jQuery-Multiple-Select-Plugin-For-Bootstrap-Bootstrap-Multiselect/
Related
I am doing bank account validation using ajax dynamic select. onkeyup after the acc number is entered, it runs a check from external file. Right now, I can only check the account number, I want it to be able to check the bank and acc number. I simple want to GET the value of bank and account to be used for the validation in validate_acc.php.
<script>
function dynamic_Select3(ajax_page, account) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + account,
//data: "ch2=" + bank,
dataType: "html",
//dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult3").html(html); }
});
}
</script>
my html form
<td class="body_text_normal_npt">Select your Bank</td>
<td><span class="body_text_normal_npt">
<select name="bank" id="bank">
<option value="Select Values" selected="selected">-------------------------------</option>
<?php
$sql4="SELECT bankName FROM banks WHERE status = 'active'";
$banks = $mydb->query($sql4) or die(mysqli_error($mydb));
$row_banks = mysqli_fetch_assoc($banks);
$totalRows_banks = mysqli_num_rows($banks);
do {
?>
<option value="<?php echo $row_banks['bankName']?>"><?php echo $row_banks['bankName']?></option>
<?php
} while ($row_banks = mysqli_fetch_assoc($banks));
$rows = mysqli_num_rows($banks);
if($rows > 0) {
mysqli_data_seek($banks, 0);
$row_banks = mysqli_fetch_assoc($banks);
}
?>
</select>
</span></td>
</tr>
<tr>
<td class="body_text_normal_npt">Acc Number</td>
<td><p>
<input name="account" type="text" id="account" size="25" onKeyPress="return isNumberKey(event)" onKeyUp="dynamic_Select3('validate_acc.php', this.value)" />
</p>
</td>
</tr>
The validation page
//$bank= $_GET['modepayment'];
$bank= $_GET['ch2'];
$accnum = $_GET['ch'];
$query_bcode = "SELECT bankCode,abbr FROM banks WHERE bankName = '$bank'";
$bcode = $mydb->query($query_bcode) or die(mysqli_error($mydb));
$row_bcode = $bcode->fetch_assoc();
$bankCode = $row_bcode['bankCode'];
//echo $bankCode;
//echo $accnum;
$json = file_get_contents("https://api.bank.codes/ng-nuban/?format=json&api_key=2d112c21e1c5844f*******154&bank=$bankCode&nuban=$accnum");
$obj = json_decode($json);
Possible to try this? You can have multiple parameters in this way.
var request = $.ajax({
url: "ajax_page",
method: "POST",
data: { ch: account, ch2: bank},
dataType: "html"
});
Code is based on an example from http://api.jquery.com/jquery.ajax/
here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});
I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.
HTML CODE:
<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];
if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->
<?php } ?>
</SELECT>
</td>
Javascipt code:
function get_type()
{
$(".channelname").live("change", function() {
var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
}
remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript
put this
<SELECT name="channel_name[]" required class='channelname'>
and javascript
$(".channelname").change(function() {
var channel_id = $('.channelname').find("option:selected").attr("value");
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {
if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);
}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");
}
});
});
Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.
I need a little help here. I am creating a dynamic dropdown list but I don't know how to display the ajax result in an element.
Here's my scenario:
The user will choose a state in the dropdown.
After choosing the code will send an ajax request
After sending, display the result in a select option named 'cities'
So there are 2 select box. One is 'state' and second is 'cities'.
Here's my code:
Here's my jquery for accessing the controller
$('#state').on('change',function(){
var state_code = $('#state').val();
var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
success: function(){
//
}
});
});
Here's my function in the model
public function getCity($code){
$sql = "SELECT id,name FROM ref_cities WHERE province_code = '".$code."'";
$result = $this->db->query($sql);
return json_encode($result->result_array());
}
Here's the controller part
public function displayCity($code){
$x = json_decode($this->locations_model->getCity($code));
return print_r($x);
}
Here's the code in my selecting the city code
<select id="state" name="state">
<option value="">---Select State---</option>
<?php
$decode_city = json_decode($city,true);
foreach($decode_city as $m){
echo "<option value='".$m['code']."' ".set_select('state',$m['code']).">".$m['name']."</option>";
}
?>
</select>
Here's the part where should I put the ajax result
<select id="city" name="city">
<option value="">---Select City---</option>
<!-- INCLUDE LOOP TO DISPLAY cities -->
</select>
Try this,
jQuery.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
success: function(data){
//you will get the result in data
//jQuery("#someDiv").html(data);
//The parsed data is something like below
jQuery.each(jQuery.parseJSON(data), function(key,value){
jQuery("#city").append('<option value ="'+value+'">'+value+'</option>');
});
}
});
Hope its get fixed.
your success function must be something like this
$.each($.parseJSON(data), function(key,value){
$('<option/>','{value:'+value+'}').appendTo('#yourparent');
});
$('#state').on('change',function(){
var cityList = '';
var state_code = $('#state').val();
var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'String',
success: function(data){
$('#city').html(data);
}
});
});
you can rewrite your code like this. it will work
or you can try this
public function getCity($code){
$sql = "SELECT id,name FROM ref_cities WHERE province_code = '".$code."'";
$result = $this->db->query($sql);
$cities = $result->result_array();
$options = '';
foreach($cities as $city){
$options .= '<option value="'.$city["id"].'">'.$city["name"].'</option>';
}
return $options;
}
this should work try this
Do something like this
$('#state').on('change',function(){
var state_code = $('#state').val();
var city_url = 'controller_file.php?state_code=<?php echo state_code; ?>';
$.ajax({
type: 'GET',
url: city_url,
data: '',
dataType: 'json',
success: function (response) {
var response_arr = JSON.parse(response);
$.each(response_arr ,function(index,value)
{
$("#city").append("<option value="+value.id+">"+value.name+"</option>");
});
}
});
});
in controller_file.php file write this
displayCity($_GET['state_code']);
I manage to answer my question. Here's what I did
In my Controller I removed the json_decode(). And now I have this
public function displayCity($code){
$x = $this->locations_model->getCity($code);
echo $x;
}
Then I can access it in console.
$.ajax({
type: 'POST',
url: city_url,
data: '',
dataType: 'json',
async: false,
success: function(i){
console.log(i);
}
});