I have a html table with rows and child rows that are filled with data from a json array.
The problem I'm having are :
- The objects in the json array may or may not contain several object arrays, which need to be added as a child row.
- I can't get the array of child objects (interactions) out of the main object
An object of the json array is given below.
So far, I've managed to fill the table rows with data. I can also fill one child row, but only with data from the root of the object.
json object:
[
{
"name": "XXXXXXX",
"firstName": "XXXXXXX",
"contactnr1": "+123456789",
"wrapup": "WRAPUP",
"agent": "SUMO",
"date": "05/02/2019 10:10:30",
"totalAttempts": "2",
"interactions": [
{
"agent": "SUMO",
"interactionAlertStart": "02-05-2019 22:04:30",
"interactionStart": "02-05-2019 22:04:32",
"interactionCallStart": "02-05-2019 22:04:38",
"interactionCallEnd": "02-05-2019 22:05:04",
"interactionWrapupStart": "02-05-2019 22:05:16",
"interactionWrapupEnd": "02-05-2019 22:05:16",
"interactionEnd": "02-05-2019 22:05:26",
"interactionType": "XXXXX",
"interactionDuration": "54 s",
"queue": "XXXX",
"wrapup": "WRAPUP 1",
"dnis": "tel:+123456789"
},
{
"agent": "SUMO",
"interactionAlertStart": "02-05-2019 22:10:29",
"interactionStart": "02-05-2019 22:10:36",
"interactionCallStart": "02-05-2019 22:10:52",
"interactionCallEnd": "02-05-2019 22:11:00",
"interactionWrapupStart": "02-05-2019 22:11:12",
"interactionWrapupEnd": "02-05-2019 22:11:12",
"interactionEnd": "02-05-2019 22:11:14",
"interactionType": "Callback",
"interactionDuration": "37 s",
"queue": "YYYY",
"wrapup": "WRAPUP 2",
"dnis": "tel:+987654321"
}
]
},
++++++++++++++++++++++
javascript:
// function for formatting row details
function format (d) {
// 'd' is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Agent:</td>' +
'<td>Datum:</td>' +
'<td>Contactnr:</td>' +
'<td>' + d.queue+ '</td>' +
'</tr>' +
'<tr>' +
'<td>Contactnummer:</td>' +
'<td>' + d.interactionStart+ '</td>' +
'</tr>' +
'<tr>' +
'<td>TotaalPoging</td>' +
'<td>' + d.interactionEnd+ '</td>' +
'</tr>' +
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': {
'url': 'http://127.0.0.1:8088/campaigns/contacttable?orgName=xxx&campaignId=yyyy-yyyy-yyyy-yyyy',
'dataSrc': ''
},
'columns': [
{
'className': 'com-table',
'orderable': false,
'data': null,
'defaultContent': ''
},
{'data': 'name'},
{'data': 'firstName'},
{'data': 'contactnr1'},
{'data': 'totalAttempts'}
],
'order': [[1, 'asc']]
});
});
So to conclude: I want to dynamically add the data from the interactions as child rows. An object can have multiple interactions, only one interaction, or no interction.
My current javascript code is below the json array
If I understood well, you want to build the table based on this interactions array. I would start processing it. I recommend you to using the .map() method to create an array of rows.
function processResponse(res){
var interactions = response[0].interactions;
// If no interactions, you may to return a single row
if(!interactions || interactions.length === 0){
return '<tr><td>No interactions to display.</td></tr>'
}
var interactionsRows = interactions.map(function(interaction){
return '<tr>' +
'<td>Agent:</td>' +
'<td>Datum:</td>' +
'<td>Contactnr:</td>' +
'<td>' + interaction.queue+ '</td>' +
'</tr>' +
'<tr>' +
'<td>Contactnummer:</td>' +
'<td>' + interaction.interactionStart+ '</td>' +
'</tr>' +
'<tr>' +
'<td>TotaalPoging</td>' +
'<td>' + interaction.interactionEnd+ '</td>' +
'</tr>'
});
// Concatenate the rows into one string
return interactionsRows.join();
}
Once I processed the response, I just need to concatenate it in the table.
document.getElementById('table').innerHTML = processResponse(response)
See the snippet code working here.
Note you should use the DOM API to manipulate HTML elements in a better way instead to inject strings using .innerHTML. It's easier using JQuery.
Related
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>'
)
});
}
Hi People i try to do a small jquery/php/mysql chat! What i need to do ist following:
My Html
<div id="loader"></div>
My Php
$myArray = array();
if ($result = $mysqli->Query("SELECT * FROM chat AS CHA LIMIT 3 ")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
My Json Output
[
{
"CHA_id": "594",
"CHA_to": null,
"CHA_from": "1000",
"CHA_time": "2019-11-18 00:02:13",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 1"
},
{
"CHA_id": "593",
"CHA_to": null,
"CHA_from": "1004",
"CHA_time": "2019-11-17 23:56:47",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 2 "
},
{
"CHA_id": "592",
"CHA_to": null,
"CHA_from": "1004",
"CHA_time": "2019-11-17 23:56:47",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 3 "
}
]
My Jquery
I try this
$.getJSON( "https://example.com/JSON.CHAT.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
But i get only this response
[object Object]
[object Object]
[object Object]
What i need to do ist
1. Load the content into loader div from json output
2. Update div appending new content based on "CHA_time"
Every help ist wellcome im totaly blocked.
As 04FS metioned, Your JS isn't right. It should be something like this:
$.getJSON( "https://example.com/JSON.CHAT.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.CHA_message + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
All "rows" are objects, so each individual value must be used properly while trying to add it to string.
This output:
[object Object]
Is the result of what you're doing here:
items.push( "<li id='" + key + "'>" + val + "</li>" );
In this case val is one of your returned objects:
{
"CHA_id": "594",
"CHA_to": null,
"CHA_from": "1000",
"CHA_time": "2019-11-18 00:02:13",
"CHA_room": "yes",
"CHA_read": null,
"CHA_message": "Message 1"
}
But the system has no way to know how to meaningfully display that object as a simple string. Did you want to display all properties? With or without keys? A specific property? In a specific format? JavaScript doesn't/can't know. So you need to specify how to format it. For example, if you just want to display one field:
items.push( "<li id='" + key + "'>" + val.CHA_id + "</li>" );
// ^--- here
Or if you want to format two fields, separated by a hyphen:
items.push( "<li id='" + key + "'>" + val.CHA_id + " - " + val.CHA_message + "</li>" );
Basically, however you want to format it, you'd need to provide the formatting logic to do that.
I have a jQuery's datatable which gets filled up with server side data like this:
"columns": [
{
"targets": -1,
"data": "ImageURL",
"name": "Title",
"render": function (data, type, row) {
return '<td><div class="tableimage"><img src="' + data + '"/></div></td>'; //'<td><img src=' + data + '></td>';
}
},
{
"data": "Title",
"name": "Title",
"render": function (data, type, row) {
return '<td>' + data + '</td>';
}
},
{
"data": "CurrentPrice",
"name": "CurrentPrice",
"render": function (data, type, row) {
return '<td>$ ' + data + '</td>';
}
},
]
And this is fine, each column gets generated and rendered in my browser like this:
<tr>
// generated td's here...
<tr>
Now my question here is whether I can generate a custom tr tag with specially added class?
Something like this:
<tr class="myclassNameGoesHere">
</td>
Is this doable via server side data processing & jquery's datatables ?
P.S. I tried something like this:
$(row).addClass("alert-danger");
// or
row.className = "alert-danger";
But neither of these worked... :/
Firstly, you don't need to return td tags in render functions, datatables automatically created td tags for you.
So,
return '<td>' + data + '</td>';
would become
return data;
Now, to answer your question, use createdRow callback provided by datatables.
Like,
$('#example').dataTable( {
"createdRow": function( row, data, dataIndex ) {
$(row).addClass( 'alert-danger' );
}
} );
I received JSON post response as shown below . I want to iterate over JSON post response data and print the data in image divs (as shown).
Could any show me how this can be done using JavaScript ? Thanks
Javascript code the receives JSON post response :
cordovaHTTP.post(url,data,
function(response) {
alert("Data: " + response.data + "\nStatus: " + response.status);
}
post request response received:
"[\r\n {\r\n \"itemID\": \"12345678\",\r\n \"itemTitle\": \"mango\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"http://awebsite.com/pics/1.jpg\",\r\n \"Other\": null\r\n },\r\n {\r\n \"itemID\": \"12345679\",\r\n \"itemTitle\": \"orange\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"http://awebsite.com/pics/2.jpg\",\r\n \"Other\": null\r\n }\r\n]"
Image divs that i want to print :
<div class ="image">
<a href="javascript:dofunction('./test.php?title=Mango&TargetUrl=http://somesite.com/12345678')">
<img src="http://awebsite.com/pics/1.jpg" alt=".." />
</a>
</div>
<div class ="image">
<a href="javascript:dofunction('./test.php?title=orange&TargetUrl=http://somesite.com/12345679')">
<img src="http://awebsite.com/pics/2.jpg" alt=".." />
</a>
</div>
Edit: I accept the answer below and i had to validate my actual api data using some replace functions by removing all \r\n and changing all itemText key values to "itemtext": "empty", using regular expression!
You can write something like this:
cordovaHTTP.post(url, data, function(response) {
// first, convert the string to JSON data array structure
var json = $.parseJSON(response.data);
// then loop the single items
for(i in json)
{
// create HTML code
var div = "<div class=\"image\">" +
"<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=http://somesite.com/" + json[i].itemID + "')\">" +
"<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
"</a>" +
"</div>";
// append it inside <body> tag.
$("body").append(div);
}
});
IMO, use concatenate += of string rather than every time append HTML to the body inside a loop.
In addition of #Taha Paksu answer.
cordovaHTTP.post(url, data, function(response) {
// first, convert the string to JSON data array structure
var json = $.parseJSON(response.data);
// then loop the single items
var div = "";
for(i in json)
{
// create HTML code
div += "<div class=\"image\">" +
"<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=http://somesite.com/" + json[i].itemID + "')\">" +
"<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
"</a>" +
"</div>";
}
// append it inside <body> tag once the loop completes
$("body").append(div);
});
As commented before, there are 2 ways to create dynamic elements
Create html string and set it as innerHTML
Create dynamic elements using document.createElement and append it to container.
Following is a sample representing creation of HTML string:
Note: There are different ways to loop. You should choose them based on your use case. I have use array.reduce for sample but you can achieve same result using for or any other method.
var data = [{
"itemID": "12345678",
"itemTitle": "mango",
"itemText": "",
"ThumbUrl": "http://awebsite.com/pics/1.jpg",
"Other": null
}, {
"itemID": "12345679",
"itemTitle": "orange",
"itemText": "",
"ThumbUrl": "http://awebsite.com/pics/2.jpg",
"Other": null
}]
function createHTML(obj) {
var _href = "./test.php?title=" +obj.itemTitle+ "&TargetUrl=http://somesite.com/" + obj.itemID
var _html = '<div class ="image">' +
'<a href="javascript:dofunction('+_href+')">' +
'<img src="' +obj.ThumbUrl+ '" alt=".." />' +
'</a>' +
'</div>'
return _html;
}
var _html = data.reduce(function(p,c){
return p + createHTML(c)
},'');
console.log(_html)
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.