Render/display json file to html via jquery - php

how to display this json file using jquery?
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
and look like this
<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>
<td>00-002159</td> <td>SALUNGA </td> <td>JEFFERSON</td>
<td>00-002160 </td> <td>TUMANAN </td> <td>RHODA</td>
</tr>
</tbody>
</table>

jQuery.template should be a good approach to show the data.

Parse json data, the data what you mention in example is array of objects
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" },
{ "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
[] - Represents js array an {} - Represents js Object So to parse data and get RHODA use data[0].firstname;

You could try this...
<script type='text/javascript'>
var data = [ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ];
var string = "";
$.each(data, function() {
$.each(this, function(k, v) {
v += " ";
string += v;
});
});
alert(string);
</script>

see this link also very useful
Loop through JSON object List
I didn't format the string properly , please check that
Assume your json has this format
[ { "code":"00-002159", "lastname":"SALUNGA", "firstname":"JEFFERSON" }, { "code":"00-002160", "lastname":"TUMANAN", "firstname":"RHODA" } ]
Assume you have response in a codes object
var finalHtml='';
finalHtml='<table>
<thead>
<tr>
<th>code</th> <th>lastname</th> <th>firstname</th>
</tr>
</thead>
<tbody>
<tr>'
for(i=0; i< codes.length;i++)
{
//store the values and paint the html
finalHtml+=<td>0codes[i].code;</td> <td>codes[i].lastname </td> <td>JEFFERSON</td>;
}
</tr>
</tbody>
</table>'
append to the dom finally
have some container and do
$('#containerID').html(finalHtml);

Related

Display data after ajax request in codeigniter

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>

Fetch data using AJAX and Codeigniter?

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);
});
}

find an element with jquery

i have this table wrote in html with php and bootstrap:
<table id="tabela-resultado" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>Ativo</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if(count($records)) { ?>
<?php foreach($records as $record) { ?>
<tr data-id="<?php echo $record->id; ?>">
<td><?php echo $record->nome; ?></td>
<td>
<?php
if ($record->ativo == 1) {
echo "SIM";
} else if($record->ativo == 0){
echo "NÂO";
}
?>
</td>
<td>
<?php echo anchor("gurpoProduto/excluir", "<i class='glyphicon glyphicon-trash'></i> Exlcuir", ['class' => 'btn btn-danger btn-block', 'name' => 'delete']); ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
i'm trying to found an element in the first column using this function with jquery. Tihs is the function:
function verificar_existencia(nome) {
var table = $("#tabela-resultado tbody");
var nomeTabela = '';
table.find('tr').each(function (nome) {
var $tds = $(this).find('td'),
nomeTabela = $tds.eq(0).text()
});
if(trim(nome.toUpperCase()) === trim(nomeTabela.toUpperCase())) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
but doesnt work.Whats is wrong? I need find an element in the table to prevent duplicate elements in the table.
You are looping through all the rows and overwriting nomeTabela every iteration.
Thus once loop completes it is the value found in last row only and that is what your comparison is done on
Do a check inside the loop for each value on each row something like:
function verificar_existencia(nome) {
nome = nome.trim().toUpperCase();
var table = $("#tabela-resultado tbody");
var isMatch = false;
table.find('tr').each(function(nome) {
var $tds = $(this).find('td');
var nomeTabela = $(this).find('td').eq(0).text();
// compare each value inside the loop
if (nome === nomeTabela.trim().toUpperCase()) {
isMatch = true;
return false; /// break the loop when match found
}
});
if (isMatch) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
Also note your incorrect use of String#trim() which should show up as error in your browser console
Here's a way to identify a dupe strings in the first column of the table.
var $trs = $("table tr"), dupes = [];
function san(str) {
return str.text().trim().toUpperCase();
}
$trs.each(function() {
var origTd = $(this).find("td:first"), origTr = $(this);
$trs.each(function() {
var newTd = $(this).find("td:first"),
newTr = $(this),
origTrIdx = origTr.index(),
newTrIdx = newTr.index(),
origTdStr = san(origTd),
newTdStr = san(newTd);
if (
origTrIdx > newTrIdx &&
dupes.indexOf(origTdStr) < 0 &&
origTdStr === newTdStr
) {
dupes.push(origTdStr);
console.log(
'This element "' +
origTd.text() +
'" already exists!!!'
);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>unique</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</table>

Showing data table inside a table with ng-repeat (angularjs, html)

Im having troubles with showing the data that i want in the tables. I did the following sketch so you guys can figure out what i want to display:
The query i have in my php/mysql connector brings me each "Tarea" data(second table) with "proyecto" and "alerta" but i need to display "proyecto" and "alerta" only 1 time per row.
So i did this in angular to storage the data of the second table(Tarea, Termino, Estado, Nombre), while i display the data of the first table.
scope.llamada1 = function() {
$http.get("conector.php?tipoDato=query1")
.then(function(response) {
$scope.mensajeEspera = "";
$scope.datos1 = response.data;
for(var i = 0; i < $scope.datos1.length; i++){
var currentObj = $scope.datos1[i];
$scope.datos1[i].detalleProyecto = [{
"tarea":currentObj.tarea ,
"fecha_termino":currentObj.fecha_termino ,
"estado":currentObj.estado,
"nombre_completo":currentObj.nombre_completo}];
}
});
}
And in the html i get the data like this, with the table inside the last :
<table id="tablaTareas" class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Proyecto</b></td>
<td><b>Alerta</b></td>
<td><b>Tareas</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in datos1 ">
<td style="vertical-align: top;">{{x.proyecto}}</td>
<td style="vertical-align: top;">{{x.alerta}}</td>
<td style="vertical-align: top;">
<table class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Tarea</b></td>
<td><b>Termino</b></td>
<td><b>Estado</b></td>
<td><b>Responsable</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="y in x.detalleProyecto track by $index">
<td>{{y.tarea}}</td>
<td>{{y.fecha_termino}}</td>
<td>{{y.estado}}</td>
<td>{{y.nombre_completo}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
But is repeating "Proyectos" and "Alerta" and displaying 1 "Tarea" per row and not every task together per proyect and alert, an example below.
you should try to arrange your data this way
[
{
name: nombre_completo,
data: [
{
tarea,
fecha_termino,
estado
}
]
}
]
where name is the repeated data that you don't want to repeat
a little example
if you have data like
[{country: Chile, name: Martin},{country: Chile, name: Nico},{country: Peru, name: Seba},{country: Peru, name: Nicole},{country: Argentina, name: Warencita}]
try this (assuming var datos is where your data is stored)
var datos = [{country: 'Chile', name: 'Martin'},{country: 'Chile', name: 'Nico'},{country: 'Peru', name: 'Seba'},{country: 'Peru', name: 'Nicole'},{country: 'Argentina', name: 'Warencita'}]
var temp = []
var exists
var place
for(var i = 0; i < datos.length; i++){
exists = false;
for(var k = 0; k < temp.length; k++){
if(datos[i].country === temp[k].country){
exists = true;
place = k;
break;
}
}
if(exists){
temp[place].data.push({
name: datos[i].name
})
}else{
temp.push({
country: datos[i].country,
data: [{
name: datos[i].name
}]
})
}
}

take value from array and show in view

view :
<tr style="background-color:#333; color:#FFFFFF;" align="center">
<td>No</td>
<td>ID TRANS</td>
<td>NAMA</td>
<td>TGL</td>
<td>JUMLAH</td>
<td>STATUS</td>
<td>TOTAL</td>
<td>JENIS PEL</td>
<td>NAMA</td>
<td>PENGELOLAAN</td>
</tr>
<tr class="dataku"></tr>
my jquery in array
<script type="text/javascript">
$(document).ready(function() {
selesai();
});
function selesai() {
setTimeout(function() {
update();
selesai();
}, 200);
}
function update() {
$.getJSON("<?php echo base_url();?>transaksiDigorCont/ambilDataTransaksi", function(data) {
alert("jhjh");
$(".dataku").empty();
$no=1;
$.each(data.result, function() {
$(".dataku").append(
"<td>"+$no+"</td>\n\
<td>"+this['id_transaksi']+"</td>\n\
<td>"+this['nama']+"</td>\n\
<td>"+this['tgl_transaksi']+"</td>\n\
<td>"+this['jumlah']+"</td>\n\
<td>"+this['status_transaksi']+"</td>\n\
<td>"+this['total']+"</td>\n\
<td>"+this['status_pelanggan']+"</td>\n\
<td>"+this['nama_karyawan']+"</td><td>"+this['nama_karyawan']+"</td>");
$no++;});
});
}
data.result have 3 rows, but if show in view all row show in <td>No</td> , I want every index is in the header title , for example : No have value $no, ID TRANS have value this['id_transaksi'] ect
Assuming your json response is Okay, Put this class="dataku" in your your table instead of tr
<table class="dataku">
$(".dataku").append(
"<tr><td>"+$no+"</td>\n\
<td>"+this['id_transaksi']+"</td>\n\
<td>"+this['nama']+"</td>\n\
<td>"+this['tgl_transaksi']+"</td>\n\
<td>"+this['jumlah']+"</td>\n\
<td>"+this['status_transaksi']+"</td>\n\
<td>"+this['total']+"</td>\n\
<td>"+this['status_pelanggan']+"</td>\n\
<td>"+this['nama_karyawan']+"</td><td>"+this['nama_karyawan']+"</td></tr>");
$no++;});

Categories