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');
Related
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
}
});
}
This is product filter page. I want to filter data by drop down. by php and mysqli database. I fetch data from database and put in dropdown. But it is not filtering after selecting value. trying from long time. did all possible way. please help me out in this code thank you.
var colour,brand,size,achievements ;
$(function(){
$('.item_filter').click(function(){
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{colour:colour,brand:brand,size:size,achievements:achievements,sprice:$(".price1" ).val(),eprice:$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val;
}
<div class="list-group">
<select>
<option class="item_filter" value="showAll" selected="selected">Show All Products</option>
<?php
$query = "select your_achievements from info_user where user_status = '1'";
$rs = mysqli_query($con,$query) or die("Error : ".mysqli_error());
while($achievementsdata = mysqli_fetch_assoc($rs))
{
?>
<option selected="selected" class="item_filter" value="<?php echo $achievementsdata['your_achievements']; ?>"><?php echo $achievementsdata['your_achievements']; ?></option>
<?php
}
?>
</select>
</div>
try to use onchange event like this
$('select').on('change', function() {
alert( this.value );
})
and your data variable should be like this
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
make sure your all variable's value are exist.
your ajax code should be like this
$(function(){
$('select').on('change', function() {
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});
I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js
I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});
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)
}
});