Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I'm trying to read the following json file following an ajax call. The json file should be the result of a php page that produces it and sends it to an html page that receives it and shows it in a table always with ajax. Considering that it's an exercise to learn how to use ajax, I don't really have a php page like that but I simply use the "Live Server" extension on VsCode to read the json file. My question is how could I read the json file and put it in a html table?
Json file:
{
"employees": [
{
"id":1,
"name":"name1",
"surname":"surname1",
"salary":10000
},
{
"id":2,
"name":"name2",
"surname":"surname2",
"salary":2000
},
{
"id":3,
"name":"name3",
"surname":"surname3",
"salary":2000
},
{
"id":4,
"name":"name4",
"surname":"surname4",
"salary":2000
}
]
}
html file:
<!DOCTYPE html>
<html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<head>
<title>Test JSON</title>
</head>
<body>
<div>
<table id="content">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SURNAME</th>
<th>SALARY</th>
</tr>
</thead>
<tbody id="emp">
</tbody>
</table>
</div>
<script type="text/javascript">
$.ajax({
url: "output.json",
type:"GET",
dataType:"json",
success: function (data) {
var json = JSON.parse(data.d);
$(json).each(function (index, item){
ID = json[index].id;
NAME = json[index].name;
SURNAME = json[index].surname;
SALARY = json[index].salary;
$('tbody#emp').append(
'<tr>' +
'<td>' + ID + '</td>' +
'<td>' + NAME+ '</td>' +
'<td>' + SURNAME+ '</td>' +
'<td>' + SALARY + '</td>' +
'</tr>'
)
});
},
error: function (data) { alert("help"); }
});
</script>
</body>
</html>
The final result should be an html table like this:
ID
NAME
SURNAME
SALARY
1
name1
surname1
10000
2
name2
surname2
2000
3
name3
surname3
2000
4
name3
surname4
2000
**Thanks in advance **
UPDATE:
it gives me an error at line 32 or at the following line
SALARY = json[index].salary;
the error is as follows
The AJAX returns a parsed object, so when you try to parse it with JSON.parse(data.d) it fails.
Also it seems you forgot the array you want to display is under the employees key.
Here's the corrected version of the success callback:
success: function (data) {
var employees = data.employees;
$(obj).each(function (index, item) {
ID = employees[index].id;
NAME = employees[index].name;
SURNAME = employees[index].surname;
SALARY = employees[index].salary;
$('tbody#emp').append(
'<tr>' +
'<td>' + ID + '</td>' +
'<td>' + NAME + '</td>' +
'<td>' + SURNAME + '</td>' +
'<td>' + SALARY + '</td>' +
'</tr>'
)
});
}
Related
It's my first time using json and I'm trying to make an update button on a table that i make with ajax json, there is a problem that i can't put id_news attribute on the tag along with the target link. I tried put it next to the target link, but it doesn't work, and even the tables doesn't show anything, is there any way to make it work?
$(document).ready(function() {
display_data_info();
function display_data_info() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url()?>/information/data_read_info',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var no;
var id_news;
for (i = 0; i < data.length; i++) {
no = +1;
html += '<tr>' +
'<td>' +
no +
'</td>' +
'<td>' +
data[i].news_title +
'</td>' +
'<td>' +
data[i].news_info +
'</td>' +
'<td>' +
data[i].news_status +
'</td>' +
'<td><a href="<?php echo site_url("information/display_update_info/".data[i].id_news); ?>" class="btn btn-app">' +
'<i class="fas fa-edit"></i> ' +
'</a>' +
'</td>' +
'</tr>';
}
$('#show_data_info').html(html);
}
});
}
});
[wanted to post just a comment, but haven't enough reputation yet. Perhaps a moderator can change my feedback into a comment?]
I see multiple typos and mistakes here:
In the first php part, put a ; after base_url()
You are not initializing no before you do no += 1
Instead of no += 1 you do no = +1 (which may accidentally overcome the previous error but it's probably not what you want)
In the <td><a href=.... line you are mixing up single and double quotes
In that same line, your javascript variable is inside PHP. data[i].id_news does not exist in PHP scope.
Check your web console and PHP error log, there will be several errors.
I'm using Ajax for Crud operations in laravel 5.6 and I want to reload my table after insertion of data into the table.
This is how my table looks like without data:
After insertion, table looks like this:
Even after the data is added, when i search it doesn't consider the newly appended data in the table so my search result remains - no data available in the table.
The site.js
$(".complete-table").each(function(){
$(this).DataTable( {
dom: 'Bfrtip',
buttons: [
// 'copyHtml5',
// 'excelHtml5',
// 'csvHtml5',
// 'pdfHtml5'
]
} );
});
I tried a couple of things but it didn't work for me.
The HTML for the table
<table id="asset-{{ $asset_receive->asset_received_id }}" class="complete-table table toggle-circle table-hover" data-page-size="15">
<thead>
<tr>
<th> Tag ID</th>
<th> Asset Category </th>
<th> Manufacturer</th>
<th> Serial Number </th>
<th> Model Number </th>
<th> Colour</th>
</tr>
</thead>
<tbody id="asset-table-{{ $asset_receive->asset_received_id }}">
#foreach($assets->where('asset_received_id', '=', $asset_receive->asset_received_id) as $asset)
<tr>
<td>{{ $asset->tag_id}}</td>
<td>{{ $asset->asset_categories['category']}}</td>
<td>{{ $asset->manufacturers['manufacturer']}}</td>
<td>{{ $asset->serial_number}}</td>
<td>{{ $asset->model_number}}</td>
<td>{{$asset->colour}}</td>
</tr>
#endforeach
</tbody>
Here is my Js function for the adding data into the table.
$(document).on('click', 'button.submit-asset-received', function() {
assetReceivedId = $(this).data('asset-received-id');
assetFormId = 'form#form-assets-record-' + assetReceivedId;
$('.error').addClass('hidden');
$.ajax({
type: 'post',
url: '/addAsset',
indexForm: assetFormId,
indexValue: $(assetFormId + ' input[name=asset_a_category_name]').val(),
indexManufacturer: $(assetFormId + ' select[name=a_manufacturer_id] option:selected').text(),
data: {
'_token': $(assetFormId + ' input[name=_token]').val(),
'tag_id': $(assetFormId + ' input[name=tag_id]').val(),
'asset_category_id': $(assetFormId + ' input[name=asset_a_category_id]').val(),
'manufacturer_id': $(assetFormId + ' select[name=a_manufacturer_id] option:selected').val(),
'serial_number': $(assetFormId + ' input[name=serial_number]').val(),
'model_number': $(assetFormId + ' input[name=model_number]').val(),
'colour': $(assetFormId + ' input[name=colour]').val(),
'asset_received_id': assetReceivedId,
},
success: function(data) {
if((data.errors)){
var errors = data.errors;
$.each(errors, function (key, value) {
$('input[name=' + key + ']').next('p').removeClass('hidden');
$('input[name=' + key + ']').next('p').text(value);
if(key === 'manufacturer_id'){
$('select[name=a_manufacturer_id]').next('p').removeClass('hidden');
$('select[name=a_manufacturer_id]').next('p').text(value);
}
});
}else{
$('#asset-table-'+data.assets.asset_received_id).append("<tr>"+
// "<td>" + data.asset_category_id + "</td>"+
"<td>" + data.assets.tag_id + "</td>"+
"<td>" + this.indexValue + "</td>"+
"<td>" + this.indexManufacturer +"</td>"+
"<td>" + data.assets.serial_number + "</td>"+
"<td>" + data.assets.model_number + "</td>"+
"<td>" + data.assets.colour + "</td>"+
"</tr>");
var aTable = $('#asset-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.ajax.reload();
$('#unassigned').html(data.view_1);
if(data.asset_received.qty_received != data.asset_received.qty_recorded){
$("form#form-assets-record-" + data.assets.asset_received_id).show();
}else{
$("form#form-assets-record-" + data.assets.asset_received_id).hide();
}
//increase quantity recorded of this asset by taking current value and increasing by one
var currentRecordedQuantity = parseInt($("td#qty_recorded_"+data.assets.asset_received_id).text());
console.log(currentRecordedQuantity);
$("td#qty_recorded_"+data.assets.asset_received_id).text(currentRecordedQuantity+1);
$('input[name=tag_id]').val('');
$('select[name=a_manufacturer_id]').val('');
$('input[name=serial_number]').val('');
$('input[name=model_number]').val('');
$('input[name=colour]').val('');
}
}
});
});
I tried using two different ways(in the js function for adding the asset) to solve the problem but they both failed and i don't know whether i did it wrongly.
First method
var aTable = $('#asset-table-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.ajax().reload();
Second method
var aTable = $('#asset-table-'+data.assets.asset_received_id).parent('table').dataTable();
aTable.fnDraw();
is there a better way of reloading the table to notice any newly added data?
Any suggestions will be welcomed, thanks in advance.
I think you are looking for .draw()
https://datatables.net/reference/api/draw()
In success of your ajax call, simply do:
var table = $('.complete-table').DataTable();
table.draw();
There is method called
var table = $('.complete-table').DataTable();
table.ajax.reload();
Ok you first to tell your ajax request what you will receive so
$.ajax({
type: 'post',
url: '/addAsset',
indexForm: assetFormId,
dataType:'html',
now your return will be in separated blade file
in your controller will return
return view('table',compact('data_that_you_fetched_form'));
now in your table.blade file add the html
#foreach($data_that_you_fetched_form as $asset)
<tr>
<td>{{ $asset->tag_id}}</td>
<td>{{ $asset->asset_categories['category']}}</td>
<td>{{ $asset->manufacturers['manufacturer']}}</td>
<td>{{ $asset->serial_number}}</td>
<td>{{ $asset->model_number}}</td>
<td>{{$asset->colour}}</td>
</tr>
#endforeach
and finally add it to your table
success: function(data) {
$(asset-table-'{{ $asset_receive->asset_received_id }}').html(data);
}
I think that will work fine and clean and easy to modify
Currently working on jQuery auto complete where I can able to generate data from JSON single column data, but I want two values should be displayed label and descirption
this is my json
[{"id":"Emirates College of Technology- UAE","label":"COL000001","value":"COL000001"}, {"id":"Al Khawarizmi nternational ollege- UAE","label":"COL000002","value":"COL000002"}, {"id":"Syscoms ollege","label":"COL000003","value":"COL000003"}, {"id":"Abounajm Khanj Pre-Uni enter","label":"COL000004","value":"COL000004"}, {"id":"Advanced lacement","label":"COL000005","value":"COL000005"}, {"id":"Al Buraimi College Uni Clge)","label":"COL000006","value":"COL000006"}, {"id":"Al-Ain Community ollege","label":"COL000007","value":"COL000007"}, {"id":"AMA Computer ollege","label":"COL000008","value":"COL000008"}, {"id":"Arab Academy for Bankg nd Fin","label":"COL000009","value":"COL000009"}, "id":"ARABACDSCITECHMARTIMETRNS","label":"COL0000010","value":"COL0000010"}, "id":"Arapahoe Community College","label":"COL0000011","value":"COL0000011"}, {"id":"Other","label":"Other","value":"Other"}]
Here is my jquery code
$("#scl_name").autocomplete({
highlightClass: "bold",
source: function( request, response ) {
var regex = new RegExp(request.term, 'i');
//var filteredArray = filteredArray.slice(0,10);
$.ajax({
url: "json/dummy.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
if(regex.test(item.label)){
var html="";
html += "<table>";
html += " <tr>";
html += " <td>"+addslashes(item.label)+"</td>";
html += " <td>"+addslashes(item.id)+"</td>";
html += " </tr>";
html += "</table>";
return {
value: html,
value: item.id,
value: item.label
};
}
}));
},
});
},
select: function(event, ui) {
$('#school_Name').val(ui.item.id);
}
});
});
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
With this above code I am getting the data, for first column but not for second column in second column i am getting the value as undefined
what I am doing wrong here?
ReferenceError: Item is not defined
html += " <th>" + Item + "</th>";
Well, here it goes my help. When dealing with JSON is better if you can be sure that you are receiving what you are expecting, first of all. To do this you have a function called .success on your AJAX response and this parses each JSON item (this will be your first item: {"id":"Emirates College of Technology- UAE","label":"COL000001","value":"COL000001"})
To be sure you are receiving the id, label and value elements I will do something like this inside your success function:
console.log(item.id);
console.log(item.label);
console.log(item.value);
or just directly
console.log(item); // this will be presented as an object you can examine on your chrome browser, for example.
if you are sure you are getting the values on the client then I will be fixing the problem you are having when returning from the function, as you may know you can only return one value, not three:
return {
value: html,
value: item.id,
value: item.label
};
Change it to :
return {
value: html,
};
as you seem to be creating the entire value already. If this is not your issue, please post back again.
If you want to add a heading this will do it:
var html = "";
html += "<table>";
html += " <tr>";
html += " <th>" + Title + "</th>";
html += " <th>" + Description + "</th>";
html += " </tr>";
html += " <tr>";
html += " <td>" + addslashes(item.label) + "</td>";
html += " <td>" + addslashes(item.id) + "</td>";
html += " </tr>";
html += "</table>";
I want to implement a Datatable into a theme, which gets the data via an Ajax Request. Once the document is loaded, I build the HTML part for the datatable. The problem is: Once I click a sort function (for example sort one row ascending) it uses the original data to sort (which is given in the .php file) instead of the new JQuery loaded datatable. So probably I need to reinitialize the datatable or anything else?
HTML Part:
<tbody id="accountList">
<!-- List all accounts -->
<tr>
<td>username#hostname-de</td>
<td>PS</td>
<td>350000</td>
<td>45000</td>
<td>Victor Ibarbo</td>
<td>30 / 30</td>
<td>224500</td>
<td><label class="label label-success">Online</label></td>
</tr>
</tbody>
JQuery part:
function buildAccountList(){
$.ajax({
url: "/database/accounts.php",
type: "POST",
data: {action: "selectAccounts"},
success: function (response) {
var opt = '';
$.each(response, function(i, e){
opt +='<tr>';
opt += '<td>' + e.email + '</td>';
opt += '<td>' + e.platform + '</td>';
opt += '<td>' + e.coins + '</td>';
opt += '<td>' + e.password + '</td>';
opt += '<td>' + e.tradepileCards + '</td>';
opt += '<td>' + e.tradepileValue + '</td>';
opt += '<td>' + e.enabled + '</td>';
opt += '</tr>';
});
$('#accountList').html(opt);
},
dataType: "json"
});
}
The creation of the table works fine, but as I described, once I press a sort function it uses the old table (given by the html file). I hope you guys can help me.
Are you using the jQuery DataTables plug-in? If so, they already have built-in functionality for ajax data sources: DataTables with AJAX
Alternatively, I think you should rather try to modify the table data itself in javascript instead of the rendered HTML. Using the DataTable API, especially table.clear(), table.rows.add() followed by a table.draw()(also check here), you should be able to update the data properly and use the order functionality afterwards.
In response to the comment:
Basically something like this should be enough as an initialization of the datatable:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": 'your url here'
});
});
Then your json should be organized as:
{
"data": [
[
'your columns',
...
],
]
}
If you want to not name the top-level key of your data 'data' you could set it by initializing with
"ajax": {
"url": "data/objects_root_array.txt",
"dataSrc": "your top-level key (or nothing for a flat array"
}
And as last option you can use objects instead of arrays in your ajax by adding a columns option to the initialization:
"ajax": ...,
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
...
]
and return json with objects like that:
{
"email": "some#email.com",
"platform": "PS",
"coins": "320,800",
...
}
By the way, using this you would not even have to add a tbody to the table in the first place at it should be automatically be created by the plugin once it gets the AJAX data.
Ok, so I have a table with each row having check boxes at the start of each table row. When a user clicks the table rows he/she wants to display and hits the submit button I want those table rows to show up on another page. I am doing this by creating a variable just like this:
$('#submit').click(function(){
var data;
var title = $('#dimTableTitle td').html();
data = '<table id="dimTable">';
data += '<tbody>';
data += '<tr id="dimTableTitle">' + '<td colspan="100">' + title + '</td>' + '</tr>'
data += '<tr id="dimHeading">';
$("#dimHeading").find('td').each(function(){
data += '<td>' + $(this).html() + '</td>';
});
$('#dimTable tr').has(':checkbox:checked').each(function(){
data += '<tr>'
$(this).find('td').each(function(){
data += '<td>' + $(this).html(); + '</td>'
});
data += '</tr>'
});
data += '</tr>'
data += '</tbody>';
data += '</table>';
});
The variable 'data' displays just fine on the original page but when I try and load it into a new div or other container on a different page I only receive the entire table, not the selected table rows. I want to display that new variable onto a new page that pops up when a user clicks on the submit button. Any help would be appreciated.
You can send data with post method, (async)
jQuery.ajax({
url: "a.php?" + params,
async: false,
cache: false,
dataType: "html",
success: function(html){
returnHtml = html;
}
});
Note 1: Source code is written just to give you ideas.
Local storage is the way to go.
http://www.w3schools.com/html/html5_webstorage.asp