I would like to change table value using ajax - javascript

I have a select-option and i choose one,i wanna change tablo value from database.
In my View :
<select id="Room" >
<option value="Joseph">Joseph Room</option>
<option value="Macro">Macro Lounge</option>
</select>
<table>
<tr>
<td>Day</td>
<?php
foreach ($posts as $post)
{
echo "<td>{$post->seancehour}</td>";
}
?>
</tr>
<tr>
<td><?php echo $post->seanceday; ?></td><td><?php echo $post->seancename; ?></td>
</tr>
</table>
I use ajax and want to change dynamiccally table value.My javascript is :
<script type="text/javascript">
$(document).ready(function () {
$('#Room').change(function () {
var room = document.getElementById("Room").value;
$.ajax({
type: 'POST',
data: {room: room},
url: '<?php echo site_url('Homepage/index'); ?>',
success: function (result) {
alert(result);//I dont know what has to be here.
}
});
});
});
</script>
In my Controller,I go mymodel and get database value.
public function index()
{
$room = $this->input->post('room');
if ($room == 'Macro')
{
$this->data['pasts'] = $this->SeanceModel->getMacro();
}
else
{
$this->data['posts'] = $this->SeanceModel->getJoseph();
}
$this->load->view('Homepage', $this->data);
}
For example when i open the page day=Sunday hour=12pm,if i change joseph or macro,this values must be change in the table.

Related

Append data working after trigger at third time?

I want to make a dynamic dropdown using selectpicker bootstrap library, codeigniter 4, and AJAX.
I got a problem when I trigger to select the first dropdown, the second dropdown's option appended at third times select. Here I provide the video :
https://youtu.be/AVUBlhajZ_k
Here is my code:
MODEL :
function barangBySupp($namaSupp)
{
$supp = $namaSupp;
$data = $this->db->query("SELECT * FROM tablebarang WHERE supplier='$supp'");
$result = $data->getResultObject();
return $result;
}
CONTROLLER :
public function post()
{
$request = service('request');
if ($request->isAJAX()) {
$namaSupp = $request->getVar('id');
$data = $this->barangMasukModel->barangBySupp($namaSupp);
echo json_encode($data);
}
}
JAVASCRIPT
$("#selectOptSupp").on('changed.bs.select', function(e, clickedIndex, isSelected, previousValue){
const id = $('#selectOptSupp option:selected').data('nama');
const alamat = $('#selectOptSupp option:selected').data('alamat');
const noTelp = $('#selectOptSupp option:selected').data('notelp');
$('[name=namaSupp]').val(id);
$('[name=alamatSupp]').val(alamat);
$('[name=noTelp]').val(noTelp);
$.ajax({
type: "post",
url: "/BarangMasuk/post",
dataType: "JSON",
data: {
id: id
},
cache: false,
success: function(response) {
$.each(response, function(index, data){
$('#selBarang').append('<option data-nama="'+data['namaBarang']+'" data-harga="'+data['harga']+'" data-unit="'+data['unit']+'" value="'+data['namaBarang']+'" data-tokens="'+data['namaBarang']+'">'+data['namaBarang']+'</option>').selectpicker("refresh");
});
SHORT VIEW CODE :
<select id="selectOptSupp" class="form-control selectpicker" data-live-search="true">
<?php foreach ($supplier as $value) : ?>
<option data-nama="<?= $value['namaSupp']; ?>" data-notelp="<?= $value['noTelpSupp']; ?>" data-alamat="<?= $value['alamatSupp']; ?>" data-tokens="<?= $value['namaSupp'] ?>" name="" value="<?= $value['namaSupp'] ?>"><?= $value['namaSupp'] ?>
</option>
<?php endforeach; ?>
</select>
<select id="selBarang" class="form-control selectpicker" data-live-search="true">
// OPTION DATA SHOULD APPEND HERE WHEN #selectOptSupp fires
</select>

Dynamic Dependent Dropdown List Country and State on Code Igniter

I am working on project that uses a dynamic or dependent dropdown list on CodeIgniter. This is my noob logic, the country value from Views passed to Models, then the Models get state data with same country value from Views, then Controllers get state data from that Models and pass it again to Views. And the problem is the state dropdown list show nothing.
Sorry, iam new in coding.
//This is the Controllers (Pkl.php)
$data['all_country'] = $this->Server_Model->get_country_model();
$data['all_state'] = $this->Server_Model->get_state_model();
$this->load->view('contents/page_dashboard', $data);
//This is the Models (Server_Model.php)
function get_country_model(){
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("country");
$que = $db_jarlap->get();
return $que->result();
}
function get_state_model(){
$kakakoko = filter_input(INPUT_POST, 'country_id');
$db_jarlap = $this->load->database('gis_bali', TRUE);
$db_jarlap->select("*");
$db_jarlap->from("state");
$db_jarlap->where(" id_country = $kakakoko ");
$que = $db_jarlap->get();
return $que->result();
}
//This is the Views Content (page_dashboard.php)
<script src="<?php echo base_url() ?>resources/js/jquery-3.3.1.min.js"</script>
<script>
$(document).ready(function(){
$('#formCountry').change(function(){
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ? >application/models/Server_Model.php",
method: "POST",
data: {country_id:country_id},
success: function(data) {
$('#formState').html(data);
}
});
});
});
</script>
<select name="formCountry" id="formCountry">
<?php foreach($all_country as $semua_country): ?>
<option value="<?php echo $semua_country->id_country; ?>"><?php echo $semua_country->nama_country; ?></option>
<?php endforeach; ?>
</select>
<select name="formState" id="formState" >
<?php foreach($all_state as $semua_state): ?>
<option value="<?php echo $semua_state->id_state; ?>"><?php echo $semua_state->nama_state; ?></option>
<?php endforeach; ?>
</select>
Thanks for your help.
You should not directly call model, instead call the Pkl controller, I'm assuming that you are using the index() method on Pkl controller :
$(document).ready(function () {
$('#formCountry').change(function () {
var country_id = $(this).val();
$.ajax({
url: "<?php echo base_url() ?>pkl", // using Pkl controller
method: "POST",
data: {
country_id: country_id
},
success: function (data) {
$('#formState').html(''); // empty the select option element
$.each(data, function(){ // format each option returned from Pkl controller
$("#formState").append('<option value="'+ this.id_state +'">'+ this.nama_state +'</option>');
});
}
});
});
});

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

want to update dropdown in each row in the database using Ajax

Here is my UI Screenshot. Highlighted is the Dropdown
What i want?
As i Select any option in the Dropdown it should get updated for that particular row in Database using AJAX
Below are the Codes that i've written. I'm just a Beginner, please excuse if the code is not neat!!
I'm using Codeigniter
Front End
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
Ajax Code - I've added a Console.log to see weather next row dropdown is being selected or not
$(document).ready( function() {
$(".statusClass").change(function(event) {
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $("select.statusClass").val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
*Console Ouputs for the first 3 rows show the 1 row selection thrice - Below is the Screeshots of that *
You are checking the values of all select box. Instead of that you get the values which you are updating to obtain the result this keyword will use.
$(document).ready( function() {
$(".statusClass").change(function(event) {
var status = $(this).val();

Not found when using ajax in dynamic dropdown in php

In my php code, I have two dropdowns which is the other one depends on the first one.
Here is the first dropdown:
<select class="form-control style" id="sel" >
<option style="color: black;" >Select...</option>
<?php foreach ($dtype as $row ) { ?>
<option style"color:black;" value="<?php echo $row['donations_type_id'];?>"> <?php echo $row['donations_type_name'];?></option>
<?php }?>
</select>
<tr>
<td>Available Donation:</td>
<td style="color: black; ">
<select name='avail' id='avail' class="form-control style" >
<option style="color:black;" value="">Select...</option>
</select>
</td>
</tr>
The second dropdown shows the data that corresponds whatever the user selects from the first dropdown.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
type: "POST",
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
success:function(data){
$("#avail").html(data);
}
});
});
});
</script>
In my controller:
public function showAvailable()
{
echo $id = $this->input->post('id', true);
$data['package'] = $this->Beneficiary_model->getDtype($id);
$output = null;
foreach ($data['package'] as $row ) {
$output.="<option value='".$row->package_id."'>".$row->package_name."</option>";
}
echo $output;
}
And in my model:
public function getDtype($id){
$this->db->select('package_id','package_name');
$this->db->from('package_table');
$this->db->where('package_type', $id);
$query = $this->db->get();
return $query->result();
}
When I tried to run the code and debug it through F12, it shows there that POST http://localhost:8999/samp/sampModule/showAvailable/2 404 (Not Found)
Why is it?
Can anyone help me with this error?
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
Take $(this) out of ajax object. It points now to ajax object itself. Try:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
**UPDATED**
Also, if the data is received from the server correctly but dropdown is still not rendered, the issue might be with the dataType property. There may be some problems with the response mime type, that cause the problem with the Intelligent Guess and data is treated as a json or xml string, so you can try to set it explicit:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
type: "POST",
dataType: 'html',
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
success:function(data){
$("#avail").html(data);
}
});
});

Categories