I am using Ajax request to fetch data from database. All I want to do is to display the result in tabular form whenever we select an option from the option list. I am also able to do that but when I am choosing another option the view for the previous option it is not removed from the table.
View:
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
Controller:
public function getBranchDetail(){
$branch = array();
$city_id = $this->input->post('city_id');
if($city_id){
$con['conditions'] = array('id'=>$city_id);
$branchData = $this->Bank_model->getBranchData($con);
}
echo json_encode($branchData);
}
Model:
function getBranchData($params = array()){
$this->db->select('c.micr_code, c.ifsc_code, c.contact_no, c.address');
$this->db->from($this->branchTbl.' as c');
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach ($params['conditions'] as $key => $value) {
if(strpos($key,'.') !== false){
$this->db->where($key,$value);
}else{
$this->db->where('c.'.$key,$value);
}
}
}
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
//return fetched data
return $result;
}
When I am selecting a city from option it is showing me the result for that city which is correct. When I am choosing another city from the option it is showing the result also, but the result for the previous option is not removed from the table. I want to remove the previous record when I am selecting another option.
Check the below code ( not tested ). Clear the contents before appending data in the loop.
$('#city').on('change',function(){
var cityID = $(this).val();
// alert(cityID);
$.ajax({
type:'POST',
url:'<?php echo base_url('bank/getBranchDetail'); ?>',
data:'city_id='+cityID,
success:function(data){
var dataObj = jQuery.parseJSON(data);
// clear the data before appending
$('#ifsc').html("");
$('#micr').html("");
$('#contact').html("");
$('#address').html("");
$(dataObj).each(function(){
var ifsc = $('<p />');
var micr = $('<p />');
var contact = $('<p />');
var address = $('<p />');
// alert(option);
ifsc.attr('value', this.id).text(this.ifsc_code);
micr.attr('value', this.id).text(this.micr_code);
contact.attr('value', this.id).text(this.contact_no);
address.attr('value', this.id).text(this.address);
$('#ifsc').append(ifsc);
$('#micr').append(micr);
$('#contact').append(contact);
$('#address').append(address);
});
// $('#hodm_results').html(data);
}
});
});
<table class="table table-bordered table-hover table-full-width" id="table_userinfo">
<thead>
<tr>
<th>IFSC Code</th>
<th>MICR Code</th>
<th>Contact No.</th>
<th>Address</th>
</tr>
<tr>
<td id="ifsc"></td>
<td id="micr"></td>
<td id="contact"></td>
<td id="address"></td>
</tr>
</thead>
</table>
Related
I'm still new to php programming and I'd like to understand why my Angular Function stopped working when I'm using my jquery ajax method post where I update values on my database.
Here is my code on my angular on html:
<tfoot ng-app="kembalianApp" ng-controller="kembalianCtrl">
<tr>
<th class="has-text-right" colspan="6">TOTAL : </th>
<th class="has-text-right" ><p ng-model="total" ng-init="total='<?php echo $record2['total'];?>'"><?php echo $total;?></p></th>
</tr>
<tr>
<th class="no-border has-text-right" colspan="6">BAYAR : </th>
<th style="max-width:100px;padding:0" class="no-border"><input type="text" class="input has-text-right has-text-weight-bold" ng-model="bayar"></th>
</tr>
<tr>
<th class="no-border has-text-right" colspan="6">KEMBALIAN : </th>
<th class="no-border has-text-right">{{kembalian()}}</th>
</tr>
</tfoot>
and this is how my angular code
var app = angular.module('kembalianApp', []);
app.controller('kembalianCtrl', function ($scope) {
$scope.kembalian = function () {
if (parseInt($scope.bayar - $scope.total) >= 0) {
return $scope.result = parseInt($scope.bayar) - parseInt($scope.total);
} else {
return $scope.result = '-';
}
};
});
and this is my Jquery ajax code
$(document).ready(function () {
$('.kurang').on('click', function () {
var id_pesanan = $(this).data('id_pesanan');
var id_makanan = $(this).data('id_makanan');
var jumlah = $(this).data('jumlah');
jumlah = parseInt(jumlah);
jumlah = jumlah - 1;
$.post('assets/ajax/kurangmenu.php', {
id_makanan: id_makanan,
id_pesanan: id_pesanan,
jumlah: jumlah
}, function (data) {
$('#containerpesanan').html(data);
});
});
$('.tambah').on('click', function () {
var id_pesanan = $(this).data('id_pesanan');
var id_makanan = $(this).data('id_makanan');
var jumlah = $(this).data('jumlah');
jumlah = parseInt(jumlah);
jumlah = jumlah + 1;
$.post('assets/ajax/kurangmenu.php', {
id_makanan: id_makanan,
id_pesanan: id_pesanan,
jumlah: jumlah
}, function (data) {
$('#containerpesanan').html(data);
});
});
});
I don't get why my angular wont work after I use jquery ajax.
Here is the error in your AngularJS code: -
<p ng-model="total" ng-init="total='<?php echo $record2['total'];?>'"><?php echo $total;?></p>
ng-model is working for two-way binding. p tag is not supported for ng-model. if you want to bind p tag then you can use ng-bind or {{}}.
<p ng-bind="total"></p>
or
<p {{::total}}></p>
I'm not looking to add to / append an existing table. My table is empty until results are returned via AJAX. I'm trying to sort my tables data via the javascript plugin, tablesorter.js.
I have sorted my table so It's split between header and body. I can't seem to get the table rows to change though
My Code for the AJAX is;
<script>
$(document).ready(function()
{
$("#results").tablesorter();
}
);
</script>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#to_date").datepicker();
});
var to_date = $('#to_date').val();
$( "#genre" ).val();
{
var value = $(this).val();
$( "#price" ).val();
{
var value = $(this).val();
$('#filter').click(function(){
var to_date = $('#to_date').val();
var request = $("#genre").val();
var request1 = $("#price").val();
var data = 'to_date'+'request'+'request1';
if(to_date != '' )
{
$.ajax({
url:"filter.php",
method:"POST",
data: { to_date:to_date, request:request,request1:request1 },
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
});
}
else
{
alert("Please Select Date");
}
});
};
};
});
</script>
and my code for the html / PHP is;
<table id="results" class="tablesorter">
<thead>
<tr>
<th>Event</th>
<th>Venue</th>
<th>Genre</th>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["event_name"]; ?></td>
<td><?php echo $row["venue_name"]; ?></td>
<td><?php echo $row["genre"]; ?></td>
<td><?php echo $row["event_date"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
you never actually called to the plugin:
$("results").tablesorter()
Everytime you get your data updated you should make a all to the tablesorters update trigger so it gets its references updated.
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
that should do the trick
I am trying to fetch data into a table and nothing happens.
No table appears
No data is fetched
Controller
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
$this->load->model("usersmodel");
$data["allu"]=$this->usersmodel->ShowAllUsers("users");
$data['pagetitle']=" -->All Users Using Ajax<--";
foreach ($allu as $a):
echo'<tr>
<td>'.$a->id.'</td>
<td>'.$a->username.'</td>
</tr>';
endforeach;
$this->load->view("template/admin/header",$data);
$this->load->view("users/allusersusingajax",$data);
$this->load->view("template/admin/footer");
}
}
jQuery
<script>
$(document).ready(function () {
FetchAllUserUingAjax();
function FetchAllUserUingAjax() {
$.ajax({
url:'<?php echo base_url()?>Users/indexajax',
method:"post",
success:function (data) {
$(".userdataajax table").append(data);
}
})
var action="FetchAllUserUingAjax";
$.ajax({
url:"<?php echo base_url()?>Users/indexajax",
method:"post",
data:{action:action},
success:function (data) {
$(".userdataajax table tr ").not("table tr:first").remove();
$(".userdataajax table").append(data);
Table();
}
})
}
})
</script>
Model
public function ShowAllUsers()
{
$sql=$this->db->get("users");
return $sql->result();
}
View
<div class="userdataajax table-responsive">
<table class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
Your code hints at other relevant code that is not shown. I'm taking what you show as all that needs to be known. Here's what I see based on that premise.
First, the view. Add an id to the table. It makes JQuery selectors so much easier. The JavaScript is in this file which is "users/allusersusingajax.php".
<div class="userdataajax table-responsive">
<table id='user-table' class=" table table-responsive table-bordered">
<tr>
<th>#</th>
<th>name</th>
<th>image</th>
<th> full name</th>
<th>email</th>
<th>usertype</th>
<th>status</th>
<th>reg date</th>
<th>reg time</th>
<th>delete</th>
<th>edit</th>
<th>Activate</th>
<th>disactivate</th>
</tr>
</table>
</div>
<script>
$(document).ready(function () {
function FetchAllViaAjax() {
$.ajax({
url: '<?= base_url("users/get_all_users") ?>',
method: "post",
dataType: 'html',
success: function (data) {
var table = $("#user-table");
table.not("table tr:first").remove();//your code makes it unclear why you need this
table.append(data);
}
});
FetchAllViaAjax();
}
});
</script>
The controller needs two methods. One to show the table another to get the rows. This is the file Users.php
//show the page which includes the basic <table> and header row
public function indexajax()
{
// The code and question text give no reason for this conditional test
// So I'm removing it
//if($this->input->post("action") == 'FetchAllUserUingAjax')
//{
$data['pagetitle'] = "-->All Users Using Ajax<--";
$this->load->view("template/admin/header", $data);
$this->load->view("users/allusersusingajax");
$this->load->view("template/admin/footer");
//}
}
//respond to ajax request
public function get_all_users()
{
$this->load->model("usersmodel");
$allu = $this->usersmodel->ShowAllUsers("users");
$out = ''; //if the model returned an empty array we still have a string to echo
//using PHP's output buffer to simplify creating a big string of html
ob_start(); //start output buffering
foreach($allu as $a):
?>
<tr><td><?= $a->id; ?></td><td><?= $a->username; ?></td></tr>
<?php
endforeach;
$out .= ob_get_clean(); //append the output buffer to the $out string
echo $out;
}
Read about PHP's Output Control Functions
I'd first update my model to return an array:
return $sql->result_array();
Then in your controller, you don't need to load a view:
public function indexajax()
{
if($this->input->post("action")=='FetchAllUserUingAjax')
{
//set content type
header("Content-type: application/json");
$this->load->model("usersmodel");
echo json_encode(
$this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one
);
}
}
Then in your ajax callback:
success: function(resp){
$.each(resp, function(k,v){
console.log(v);
});
}
I am doing a project for my school subject. I am confused on how to do checking data's in checkbox and when I press a submit button, it will loop to insert into my database. I manage to display/alert the data that is being checked in my data-table.
Here is my Contoller where it populates my data table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is in my view:
<div class="dataTable_wrapper">
<table id="dataTables-docs" class="table table-striped table-bordered table-hover dataTable dtr-inline" role="grid" style="width: 100%;" width="100%" aria-describedby="dataTables-material">
<thead>
<tr>
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div><!-- dataTable_wrapper -->
here is my javascript to echo the selected check box from my data-table:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
now, i want to all that is being checked to be inserted in my database like this:
(myid,selectedfromcheckbox);
here is my screenshot from database table:
Use another ajax to insert the data
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
$.ajax({
type:"post",
data: {user_id:user_id},
"url": "<?php echo site_url('admin_controls/saveData')?>",
success:function(data){
$("#info").html(data);
}
});
});
// Below code in you controller
public function saveData()
{
// code to save in controler
}
Follow this if you can...
Basically i have an order form (which begins with one row).
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
<a id="add">+</a>
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">Product Code (e.g 66203)</td>
<td width="33%">Mtrs Required (e.g 10)</td>
<td width="33%">Preview Image</td>
</tr>
<tr class="item">
<td class="prodcode"><input type="text" name="prodcode[]" id="prodcode" /></td>
<td class="meterage"><input type="text" name="meterage[]" id="meterage" /></td>
<td class="imgsample"></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
Notice the link with an ID of "add". When checked this adds a new row to the table with the same ID. Using the code below.
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last input').val('');
$('td.imgsample:last a').remove();
return false;
});
//Check for image preview
$("#prodcode").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.imgsample') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var imgsample = $this.closest('tr').find('td.imgsample')
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
});
My PHP in searchimage...
When i currently enter a product code if it is invalid it only puts the productID in td.imsample and i want it to say INVALID CODE
//Find image based on Product Code
function findimage($imageToFind) {
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = ".strtoupper($imageToFind)."";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0) {
$sql2 = "SELECT * FROM imageindex WHERE filename LIKE '".strtoupper($imageToFind)."-%'";
$stmt2 = $dbh->query($sql2);
$obj2 = $stmt2->fetch(PDO::FETCH_OBJ);
echo ($stmt2->rowCount() == 1 ? '<span>'.$obj2->path.'/'.$obj2->filename.'</span> -' : 'No Image Available');
} else {
echo 'Invalid Code';
}
}
//Call Function
findimage($_POST['imgreference']);
try this, can have code errors since I could not test at all:
jQuery Template
HTML:
<script id="template-item" type="text/x-jquery-tmpl">
<tr class="item" id="${id}">
<td class="prodcode"><input type="text" name="prodcode[]" class="prodcode-input" data="${id}" val="" /></td>
<td class="meterage"><input type="text" name="meterage[]" class="meterage-input" val="" /></td>
</tr>
</script>
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
+
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<thead>
<tr>
<th width="33%">Product Code (e.g 66203)</th>
<th width="33%">Mtrs Required (e.g 10)</th>
<th width="33%">Preview Image</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td class="imgsample"></td>
</tfoot>
</table>
<button>Submit</button>
</form>
JS:
$(function() {
var counter = 0;
//Check for image preview
var blur_event = function(ev) {
var
self = $(this),
imgsample = $("#ordertable tfoot .imgsample");
$(imgsample).html( $(this).class() ); // update the contents
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(self).val() },
function(data) {
$(imgsample).html(data);
}
);
return false;
};
//Order Form
$("#add").bind("click", function(ev) {
counter++;
var cln = $('#template-item').tmpl({id:"item-"+counter);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
$(cln).find(".prodcode-input").bind("blur", blur_event);
$(cln).appendTo('#ordertable tbody');
return false;
});
});
Your problem is most likely due to the duplicated ID. That makes your HTML document invalid. See my explanation here.