How to display the data came from controller/model using Ajax process? - javascript

I have a problem here about ajax. Actually I'm a beginner in using Ajax that's why I can't figure out my problem. I have a form that have 4 select boxes. The initial or main selectbox is the country selector. Second is the state next is city and last is barangay. My goal is like this. After the user select his'her country the second selectbox which is state will automatically change according to the user's country. And after selecting the state it will automatically change also the city and last is the barangay. It is just like a dynamic address fields. I am using codeigniter. Here's what I did. This is the process for getting the state.
In my PHP form I have this:
<tr>
<td><label style="font-weight: normal">State / Province: </label></td>
<td >
<select class="form-control" name="c_state" id="c_state">
<option value="">--Select State--<option>
</select>
</td>
</tr>
<tr>
<td><label style="font-weight: normal">Country: </label></td>
<td >
<select class="form-control" name="c_country" id="c_country">
<option value="">--Select Country--</option>
<?php
foreach($countries as $country){
if($country['country'] == 'Philippines'){
echo "<option value='".$country['code']."'selected='selected'>".$country['country']."</option>";
}else{
echo "<option value='".$country['code']."'>".$country['country']."</option>";
}
}
?>
</select>
</td>
</tr>
....
$("#c_country").on('change',function(){
var c_country = $("#c_country").val();
var var_country_selection = '<?php echo site_url("alliance_controller/get_provinces/'+c_country+'"); ?>';
console.log(c_country);
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(d){
alert(d['c_country']);
}
});
});
In my controller I have this:
public function get_provinces($id){
$country = $this->alliance_model->hhj_provinces($id);
echo json_decode($country);
}
In my model I have this:
public function hhj_provinces($id) {
$query = "SELECT * FROM ref_region_province WHERE country_code = '".$id."'";
$result = $this->db->query($query);
echo json_encode($result->result_array());
}
The output in the success in jquery which is in alert is 'undefined'. And I also use the developer tool in Chrome and I looked in the Network tab it shows the URL of my ajax together the Code. But in my preview I have something like this.
[]
No Properties
That's all guys. I just want to get the state of the country selected.

you must return a JSON object in the controller like this
public function get_provinces(){
$id = $this->input->post('id');
$country = $this->alliance_model->hhj_provinces($id);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $country));
}
then in the View
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(data){
$.each(data, function (key, value) {
console.log(value.field)
}
});

Related

How can I add select2 dynamic select box inside a while loop?

I'm trying to put a Select2 box inside a while loop. But it only works the first select tag. Although loop works fine, the select tag is not working after the first 1. how can I fix this issue?
I also tried adding printing PHP unique id to fix it. but nothing happened.
<select type="text" name="city" id="city-<?php echo $id; ?>" class="form-control"></select>
This is the javascript part:
<script type="text/javascript">
$('#city-<?php echo $id; ?>').select2({
placeholder: 'Select city',
ajax: {
url: 'processes/cities.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
I'm expecting all the select boxes to work fine. But actually, only first 1 works.
It would be helpful if you provided the loop in your code example.
The most likely problem is that your id's are not unique. If you have multiple tags with the same id then javascript will only recognize the first one.
Here's an example to demonstrate.
https://jsfiddle.net/n8vxjoc1/1/
<div id="city-1">Content</div>
<div id="city-1">Content</div>
<script>
jQuery( '#city-1' ).html( jQuery( '#city-1' ).length );
</script>
Only the 1st element will change and it will display the number 1.
From the W3C specs:
The id attribute specifies its element's unique identifier (ID).
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
You should give the select dropdowns a class and target that instead.
E.g.
https://jsfiddle.net/n8vxjoc1/1/
<select name="city" class="select2 form-control">…</select>
<select name="city" class="select2 form-control">…</select>
<script type="text/javascript">
$('select.select2').select2({});
</script>
You can take help from this link: Demo
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
PHP:
<?php
include 'config.php';// add your config details on that file
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
JS
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}

Ajax dynamic select from 2 fields

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/

Dropdown populate table ajax codeigniter

I want to make an application in ajax in codeigniter, to choose a type of product and appears a table that contains the marks the price of the product
So here is what I have done and thank you for helping me with this code.
Controller:
public function produit()
{
$data['listType']=$this->test_m->findtype();
return $this->load->view('produit',$data);//List of product types
}
public function getprod($idv)
{
$this->test_m->idv=$idv;
$prod=$this->test_m->req_prod();
header('Content-Type: application/x-json; charset=utf-8');//to display the table
echo json_encode($prod);
}
Model:
function findtype()
{
$query=$this->db->get('valve');
return $query->result(); //dropdown types
}
function req_prod()
{
if(!is_null($this->idv)){
$this->db->select('taille,reference,marque,prix,quantite ');
$this->db->where('idv', $this->idv);
$prod = $this->db->get('produit');
// if there are suboptinos for this option...
if($prod->num_rows() > 0){
$prod_arr;
// Format for passing into jQuery loop
foreach ($prod->result() as $option) {
$prod_arr[] = $option->taille;
$prod_arr[] = $option->reference;
$prod_arr[] = $option->marque;
$prod_arr[] = $option->prix;
$prod_arr[] = $option->quantite;
}
return $prod_arr;
}
}
return;
}
And view:
<div id="ess">
<select name="vl1" id="vl1">
<option>--select valve--</option>
<?php foreach($listType as $pr){?>
<option value="<?php echo $pr->idv;?>"><?php echo $pr->type?></option>
<?php }?>
</select><br>
</div>
<p>Nos produits</p>
<div id="pr1">
<table>
<tbody>
<tr id="prod">
<td><label>Produits au choix</label></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#vl1').change(function(){ //any select change on the dropdown with id options trigger this code
var idvlv = $('#vl1').val(); // here we are taking option id of the selected one.
$.ajax({
type: "POST",
url: "/test_c/getprod/"+idvlv , //here we are calling our dropdown controller and getprod method passing the option
success: function(prod) //we're calling the response json array 'suboptions'
{
$.each(prod,function(taille,reference,marque,prix,quantite) //here we're doing a foeach loop round each sub option with id as the key and value as the value
{
var opt = $('<td/>'); // here we're creating a new select option for each suboption
opt.val(taille);
opt.val(reference);
opt.val(marque);
opt.val(prix);
opt.val(quantite);
$('#prod').append(opt); //here we will append these new select options to a dropdown with the id 'suboptions'
});
}
});
});
});
</script>
The error is Failed to load resource: the server responded with a status of 404 (Not Found)
And: [Violation] Long running JavaScript task took 304ms
Before ajax add this.
var BASE_URL = "<?php echo base_url(); ?>";
In routes add,
$['test'] = 'controller/function';
and in ajax request,
url: BASE_URL + 'test';
data:{data:idvlv},
and in controller,
$this->input->post('data');

two dropdowns on one dependent dropdown codeigniter

I have this dependent dropdown function where I have a dropdown and another one depending on it,
here is the HTML
<select class="form-control" name = "PROV_ID" id = "PROV_ID">
<option></option>
<?php foreach ($content2 as $cs) {?>
<option value="<?php echo $cs->PROV_ID; ?>"><?php echo $cs->PROVINCE; ?></option>
<?php } ?>
</select>
<select class="form-control" name = 'CT_ID' id = 'CT_ID'>
<option value=""></option>
</select>
and here is the javascript
jQuery(document).ready(function(){
$("#PROV_ID").change(function() {
var PROVID = {"PROVID" : $('#PROV_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID,
url: "<?php base_url(); ?>Employees/dependent_dropdown/",
success: function(data){
var select = $('#CT_ID');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.CT_ID+"'>"+option.CITY+"</option>");
});
}
});
});
});
now I want to have one like this, but I wanted to have selected values for the first two dropdowns before the dependent one shows the values.
e.g.
first dropdown -->select a value
second dropdown -->selects a value
dependent dropdown --> gives values according to first and second dropdown.
example: select * from thistable where column1 = 'firstdropdownvalue' and column2 = 'seconddropdownvalue'
then the dropdown values would be the result.
jQuery(document).ready(function(){
$("#CT_ID").change(function() {
var PROVID_two = {"PROVID" : $('#PROV_ID').val(), "CT_ID" : $('#CT_ID').val()};
console.log(PROVID);
$.ajax({
type: "POST",
data: PROVID_two,
url: "<?php base_url(); ?>Employees/dependent_dropdown2/",
success: function(data){
var select = $('#PROVID_two');
select.html('');
$.each(data, function(i, option){
select.append("<option value='"+option.CT_IDnew+"'>"+option.CITYnew+"</option>");
});
}
});
});
});
You can try like this. Pass two selected values. Hope you understood

codeigniter csrf not work in select option

I want to make step input with select option, in this case, i make 3 step, when select first option then will show next option 2, then option 3. i am using ajax and i set $config['csrf_protection'] = TRUE; in Codeigniter config file. In first select option (#kategori) is work and show next value in second select option, but in step 3 select option (#sub1 or secon function of javascript) n't work. thank before.
This is my view:
<?php echo form_open_multipart('',array('class'=>'form-horizontal'));?>
<?php echo form_label('Kategori','id_kategori',array('class'=>'col-sm-2 control-label'));?>
<select id="kategori" name="id_kategori">
<option value=""></option>
<?php
foreach($kategori as $kategori_umum)
{
echo '<option value='.$kategori_umum->id.'>'.$kategori_umum->nama_kategori.'</option>';
}
?>
</select>
<select id="sub1" name="id_kategori_sub1"> //step 2
<option value=""></option>
</select>
<select id="sub2" name="id_kategori_sub2"> //step 3
<option value=""></option>
</select>
Ajax :
<script type="text/javascript">
$('#kategori').change(function(){
var kategori_id = $('#kategori').val();
//alert(state_id);
if (kategori_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub1";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','kategori_id':kategori_id},
dataType: 'json',
success: function(kategori_sub1, dataType) //calling the response json array 'kategori_sub1'
{
$('#sub1').empty();
$('#sub1').show();
$.each(kategori_sub1,function(id,sub1)
{
var opt = $('<option />'); // creating a new select option for each group
opt.val(id);
opt.text(sub1);
$('#sub1').append(opt);
$('#sub2').hide();
});
},
error:function(xhr)
{
alert("Terjadi Kesalahan");
}
}); //end AJAX
} else {
$('#sub1').empty();
$('#sub2').empty();
}});
$('#sub1').mouseout(function(){
var sub1_id = $('#sub1').val();
if (sub1_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub2";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','sub1_id':sub1_id},
dataType: 'json',
success: function(kategori_sub2, dataType)
{
$('#sub2').empty();
$('#sub2').show();
$.each(kategori_sub2,function(id,sub2)
{
var opt = $('<option />');
opt.val(id);
opt.text(sub2);
$('#sub2').append(opt);
});
},
error:function(xhr)
{
alert("Kesalahan");
}
}); //end AJAX
}});</script>
I suspect your problem is using wrong event mouseout.
You should be using change the same way the first one that works does.
Beyond that more information is needed about the actual requests by inspecting in browser dev tools

Categories

Resources