ajax response can not be displayed - javascript

This is my javascript function that pull the data from the following link
function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + data[i]["id"] + "</td>";
var td2 = "<td>" + data[i]["fno"] + "</td>";
var td3 = "<td>" + data[i]["attn_no"] + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3);
}
console.log(data);
});
}
This is the output of this function in console.I want to display this output in html table and also want to send to server using datatable
In this response I want to display array data in html table and also want to send this array data to server
{status: 1, data: Array(4)}
data:Array(4)
0:{id: "1", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
1:{id: "2", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
2:{id: "3", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
3:{id: "4", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"

function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var str = `<tr>
<td>${data[i].id}</td>
<td>${data[i].fno}</td>
<td>${data[i].attn_no}</td>
</tr>`;
$("#mytable").append(str);
}
console.log(data);
});
}

Related

key is not sorted in JSON array using javascript

In this I am trying to sort the data by partNo and it is perfectly sorted with this, but my problem is that the first column of the table does not sort with the rest of the columns. sr No has to be sorted with all other columns
here sr No is a key which is not sorted with other columns
let productDetails = {
"10": [{
id: "1",
partNo: "100",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
}],
"20": [{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
}]
,
"30": [{
id: "4",
partNo: "25",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
}],
"40": [{
id: "3",
partNo: "45",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}]
};
/**
* This function displays the data in the table
*/
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray);
}
function display(productStore) {
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>";
for (var key in productDetails) {
for (var weight in productDetails[key]) {
table += "<tr><td>" + key + "</td>";
table += "<td>" + productDetails[key][weight].id + "</td>";
table += "<td>" + productDetails[key][weight].partNo + "</td>";
table += "<td>" + productDetails[key][weight].productName + "</td>";
table += "<td>" + productDetails[key][weight].size + "</td>";
table += "<td>" + productDetails[key][weight].color + "</td>";
table += "<td>" + productDetails[key][weight].description + "</td>";
}
} messageTable(table);
}
/**
* function to sort an array by part No
*/
function sortByPartNo() {
let arr = [];
item = Object.keys(productDetails)
console.log(item)
item.forEach(function (index) {
productDetails[index].forEach(function (indexA) {
arr.push(indexA);
});
})
arr.sort(function (first, second) {
return parseFloat(first.partNo) - parseFloat(second.partNo);
});
console.log(arr)
printArray(arr, item)
}
/**
* function to print array in the table
*/
function printArray(arr, item) {
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><tr><th>sr No</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th></tr>";
for (let key in arr) {
table += "<tr><td>" + item[key] + "</td>";
table += "<td>" + arr[key].id + "</td>";
table += "<td>" + arr[key].partNo + "</td>";
table += "<td>" + arr[key].productName + "</td>";
table += "<td>" + arr[key].size + "</td>";
table += "<td>" + arr[key].color + "</td>";
table += "<td>" + arr[key].description + "</td>";
} messageTable(table);
}
/**
* function is to print the table
*/
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
/**
* this function is to print the message
*/
function message(message) {
document.getElementById("demo").innerHTML = message;
}
<!DOCTYPE html>
<html>
<head>
<style>
th,
td,
p,
input {
font-family: Arial, Helvetica, sans-serif;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 10px 10px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body onload="displayData()">
<h2>Product Details:</h2>
<form action="">
<input type="button" value="sortByPartNo" onclick="sortByPartNo();">
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
</form>
</body>
</html>
There's a couple ways to go about this, but the simplest would be to just construct a new objects from the original one that contains both the keys and values.
i.e. turn this:
{
"10": [{
"partNo": "100",
"size": "30",
// etc
}],
// ...
}
into this
[
{
"key": "10",
"partNo": "100",
"size": "30",
// etc
},
// ...
]
or alternatively, something like this works too. A similar approach is used in the concrete code example below.
[
{
"key": "10",
"value": {
"partNo": "100",
"size": "30",
// etc
},
},
// ...
]
Basically, we just need to bundle all the related information together before we do a sort(). After we sort, we can pass the bundled data as-is to your display functions, or we can separate them back into two lists, however you prefer.
A practical simplified example:
const data = {
1: {
color: 'blue',
size: 10,
},
2: {
color: 'green',
size: 50,
},
3: {
color: 'yellow',
size: 5,
},
}
// Object.entries() will reshape the data in a way that keeps keys and values together
// then we .sort() based on size
const sorted = (
Object.entries(data)
.sort((x, y) => x[1].size - y[1].size)
)
console.log('sorted keys and values', sorted)
// If you want, you can then split them back out into two separate array, like you had it:
console.log('sorted keys', sorted.map(x => x[0]))
console.log('sorted values', sorted.map(x => x[1]))
See this to learn about Object.entries, used in this particular example.
Scotty Jamison responded first and gave you a good description of options and alternatives. I urge you to accept his answer.
However, I figured I minus well provide my work that I had developed in response to your original question incorrectly marked as a duplicate (as you mention in the comments to your question here). It is a more fully worked out version of Scotty's first proposal, which places the outer key as a property inside the array entry.
// Just a convenience for building productDetails
let pdVal = (id,no,name,size,colors,desc) => ({
id: id,
partNo: no,
productName: name,
size: size,
color: colors,
description: desc
})
let productDetails = {
"10": [pdVal("1","100","bag","30",["Blue"],"sky bags ")],
"20": [pdVal("2","15","bottle","10",["Green", "Orange"],"plastic and still")],
"30": [pdVal("4","25","lunchbox","20",["Blue", "Red"],"fresh food")],
"40": [pdVal("3","45","pen","10",["Red", "Blue"],"gel pen ")]
};
function sortByPartNo() {
let arr = [];
for (let key of Object.keys(productDetails)) {
let obj = productDetails[key][0];
arr.push(Object.assign({}, obj, {key}));
}
arr.sort((a,b) => parseFloat(a.partNo) - parseFloat(b.partNo))
printArray(arr);
}
function printArray(arr) {
messageTable(" ");
let table = `
<table border = 1 cellpadding = 10 >
<th colspan=7 >Product Details</th>
<tr>
<th>sr No</th>
<th>Product Id</th>
<th>Part No</th>
<th>Name</th>
<th>Size</th>
<th>Color</th>
<th>Description</th>
</tr>
`;
for (let item of arr) {
console.log({arr})
table += "<tr><td>" + item.key + "</td>";
table += "<td>" + item.id + "</td>";
table += "<td>" + item.partNo + "</td>";
table += "<td>" + item.productName + "</td>";
table += "<td>" + item.size + "</td>";
table += "<td>" + item.color + "</td>";
table += "<td>" + item.description + "</td>";
}
messageTable(table);
}
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
<input type="button" value="sortByPartNo" onclick="sortByPartNo();">
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>

after refresh the page and add new data so newly added data is replaced with old data in the table [javascript]

here I'm working with localstorage in javascript
here is my code for enter productDetails in the table using a form. when i'm enter productDetails in the table and refresh the page the entered data is in the table because of localStorage. but my problem is that when I refresh the page and again add new data so that newly added data is replaced with data which is added before refresh the page. and I want all my data instead of replacing
let productDetails = {
};
/**
* this function is for get the value from form
*/
function getValue() {
let id = document.getElementById('productId').value;
let partNo = document.getElementById('productNo').value;
let productName = document.getElementById('productName').value;
let size = getRadioValue();
let color = getCheckBoxValue();
let description = document.getElementById('description').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return {
id, partNo, productName, size, color, description, date, address, companyName
};
}
/**
* function to insert data into table
*/
function insertion() {
let value = getValue();
let letter = value.productName[0];
if (!productDetails.hasOwnProperty(letter)) {
productDetails[letter] = [];
}
let object = {
weight: value.weight, id: value.id, partNo: value.partNo, productName: value.productName, size: value.size, color: value.color, description: value.description,
companyDetails: {
date: value.date,
address: value.address,
companyName: value.companyName
}
};
JSON.parse(window.localStorage.getItem('productDetails'));
productDetails[letter].push(object);
localStorage.setItem("productDetails", JSON.stringify(productDetails));
displayData();
message("");
}
/**
* this function display the data in table
*/
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray);
}
/**
* function to display table
*/
function display() {
var result = JSON.parse(window.localStorage.getItem("productDetails"));
console.log(result)
messageTable(" ");
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>weight</th><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (var key in result) {
for (var weight in result[key]) {
//let companyDetails = result[key][weight].companyDetails ? result[key][weight].companyDetails : { date: "", address: "", companyName: "" };
table += "<tr><td>" + key + "</td>";
table += "<td>" + result[key][weight].id + "</td>";
table += "<td>" + result[key][weight].partNo + "</td>";
table += "<td>" + result[key][weight].productName + "</td>";
table += "<td>" + result[key][weight].size + "</td>";
table += "<td>" + result[key][weight].color + "</td>";
table += "<td>" + result[key][weight].description + "</td>";
table += "<td>" + result[key][weight].companyDetails.date + "</td>";
table += "<td>" + result[key][weight].companyDetails.address + "</td>";
table += "<td>" + result[key][weight].companyDetails.companyName + "</td>";
}
} messageTable(table);
console.log(result)
}
What you need to do is add a check looking for the localstorage key for your data when the page loads, if the check is true then add the previous localstorage data to your productDetails object. This is the Example =>
window.onload = init;
var arr = [];
function init() {
if(localStorage.getItem("productDetails")) {
arr.push(JSON.parse(localStorage.getItem("productDetails")));
getValue(); /*Then Continue eg.Refer to a function*/
}
else {
getValue(); /*Do something eg.Refer to a function*/
}
}
The concept is when the page loads add a window.onload function to check whether the localStorage key "productDetails" exists. If the key exist then add/push the value stored by the key to the array arr in this example. If it does not exist then eg. Do something like => Refer to a function.

populate json data in tables

javascript code
$(function(){
$(".user").on("click",function(e){
e.preventDefault();
var email = $(this).data("email");
$.ajax({
data:{email:email},
type: "POST",
url: 'getUser_detail.php',
success: function(data) {
var data = JSON.parse(data);
for (var i = 0; i < data['basic'].length; i++) {
$('#inputs').append('<label>Email:</label><input type="text" readonly class="form-control-plaintext" value="' + data['basic'][i].email + '" name="email[]" size="15">');
$('#inputs').append('<label>Password:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Pass +'" name="pass[]" size="5">');
$('#inputs').append('<label>Status:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].status +'" name="pass[]" size="5">');
$('#inputs').append('<label>Acc. Address:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].Accno +'" name="pass[]" size="44">');
$('#inputs').append('<label>Balance:</label><input type="text" readonly class="form-control-plaintext" value="'+ data['basic'][i].bal +'" name="pass[]" size="10">');
}
for( var j = 0; j<data['detail'].length; j++) {
var List = ["<tr><td>" + data['detail'][i].type + "</td><td>"+data['detail'][i].DB+"</td><td>"+data['detail'][i].LD+"</td><td>"+data['detail'][i].Prof+"</td><td>"+data['detail'][i].Server_stat+"</td></tr>"];
}
$("#bodywallet").append(List);
},
});
});
})
html code
<table class="table" id="wallet">
<thead class=" text-primary">
<tr>
<th class="text-left">Type</th>
<th class="text-left">Date_Bought</th>
<th class="text-left">Expires</th>
<th class="text-left">Profit</th>
<th class="text-left">Status</th>
</tr>
</thead>
<tbody class="text-left" id="bodywallet" >
</tbody>
</table>
this is what my data should be display on table
but it is displaying the first record only
i have checked json is bringing all the required data. what i have done wrong what is the mistake.any help will be appreciated. thanks
php code
while($row2 = mysqli_fetch_array($alEmailrslt))
{
$json_array['detail'][] = $row2;
}
echo json_encode($json_array);
You are putting everything in an array I and appending it every round.
You should use something like this instead:
success: function (data) {
var data = JSON.parse(data);
var list = []; // only one array
for (var j = 0; j < data['detail'].length; j++) {
// push to this array instead of overwriting the variable
list.push("<tr><td>" + data['detail'][j].type + "</td><td>" + data['detail'][j].DB + "</td><td>" + data['detail'][j].LD + "</td><td>" + data['detail'][j].Prof + "</td><td>" + data['detail'][j].Server_stat + "</td></tr>");
}
// update html once
// the join "glues" all parts of the array into one string
$("#bodywallet").append(list.join());
}
I think your list is not getting updated every time and the simplest approach would be, please find below code snippet:
$(document).ready(function() {
this.json = {
"Students": [{
"id": "1",
"hometown": "London",
"gender": "Male",
"GPA": "8",
"name": "Lee",
},
{
"id": "2",
"hometown": "NY",
"gender": "Male",
"GPA": "9",
"name": "Shaldon",
}, {
"id": "3",
"hometown": "Paris",
"gender": "Female",
"GPA": "7",
"name": "Julie",
}
]
};
this.renderTable = function(Students) {
var tbody = document.getElementById('tbody');
tbody.innerHTML = "";
for (var i = 0; i < Students.length; i++) {
var tr = "<tr>";
tr += "<td>ID</td>" + "<td>" + Students[i].id + "</td></tr>";
tr += "<td>HomeTown</td>" + "<td>" + Students[i].hometown + "</td></tr>";
tr += "<td>Gender</td>" + "<td>" + Students[i].gender + "</td></tr>";
tr += "<td>GPA</td>" + "<td>" + Students[i].GPA + "</td></tr>";
tr += "<td>NAME</td>" + "<td>" + Students[i].name + "</td></tr>";
tr += "<hr>";
tbody.innerHTML += tr;
}
}
this.renderTable(this.json.Students);
console.log(this.json.Students);
//code for filtering//
this.Filter = function() {
var search = document.getElementById('search');
var category = document.getElementById('category');
var filteredObj = this.json.Students;
filteredObj = $.map(this.json.Students, function(val, key) {
if (search.value === val[category.value]) return val;
});
filteredObj.length>0 ? this.renderTable(filteredObj) : this.renderTable(this.json.Students);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p></p>
<input id="search" type="search">
<select id = "category">
<option value = "select">select</option>
<option value = "id">ID</option>
<option value = "hometown">HomeTown</option>
<option value = "gender">Gender</option>
<option value = "GPA">GPA</option>
<option value = "name">NAME</option>
</select>
<button onclick="Filter()">Filter</button>
<table>
<tbody id="tbody"></tbody>
</table>

Populating a table with an object with JQuery

I have an array of objects object [{Date, Count, City}]
Lets say I have this data
[{01/01/01, 10, New York}, {01/01/01, 15, London}, {01/01/01, 16, Rome},{02/01/01, 40, New York},{02/01/01, 25, London}, {02/01/01, 36, Rome}]
I want to populate an html table using JQuery and have the following result
Date | New York | London | Rome
01/01/01 | 10 | 15 | 16
02/01/01 | 40 | 25 | 36
Is it possible to generate a table similar to this with JQuery?
This is the code I have done so far
for (var i = 0; i < countResult.length; i++) {
var html = "<table><thead><tr><th>Date</th><th>City</th><th>Count</th></thead><tbody>";
for (var j = 0; j < countResult[i].length; j++) {
html += "<tr>";
html += "<td>" + countResult[i][j].date + "</td><td>" + countResult[i][j].city + "</td><td>" + countResult[i][j].count+ "</td>";
}
html += "</tr>";
html += "</tbody></table></br>";
$(html).appendTo("#div");
}
The solution for my question was:
var countResult = [
["01/01/01", 10, "New York"],
["01/01/01", 15, "London"],
["01/01/01", 16, "Rome"],
["02/01/01", 40, "New York"],
["02/01/01", 25, "London"],
["02/01/01", 36, "Rome"]
]
var cities = []
$.each(countResult, function(rowNum, row) {
var city = row[2];
if($.inArray(city, cities) < 0) cities.push(city);
});
var html = "<table><thead><tr><th>Date</th>"
+ $.map(cities, function (c) {
return "<th>" + c
}).join("") + "</tr></thead><tbody>";
var summary = {};
$.each(countResult, function
(rowNum, row) {
if(!summary[row[0]]) summary[row[0]] = {}
summary[row[0]][row[2]] = row[1];
});
$.each(summary, function (date, counts) {
html += "<tr><td>" + date;
$.each(counts, function (i, ct) {
html += "<td>" + ct ;
});
html += "</tr>";
});
$(html).appendTo("#div");
Try this code
var html='<table>';
var arObj = YOUR ARRAY OBJECT;
$(arObj).each(function(i, u) {
var Date = u[0];
var count = u[1];
var City=u[2];
html=html+'<tr><td>'+Date+'</td><td>'+count+'</td><td>'+City+'</td><td>';
});
html=html+'</table>';
Now append to html
$('#myDiv').append(html);

logic issue with spitting out data, variables being repeated

I am trying to parse out a table that has customers vertically and time stamps horizontally. what I have so far does this but repeats the time stamps from previous customers with each loop. Here is my code:
json = JSON.parse(xmlHTTP.responseText);
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++)
{
message = message + "<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++)
{
eventmsg = eventmsg + "<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message = message + eventmsg + "</tr>";
}
message = message + "</table>";
The JSON looks like this:
- collection: [
- {
- customer: {
id: "1",
name: "Mr Jones",
customer_id: "1"
}
-events: [
-{
event_id: "1",
time_stamp: "1377083342"
}
-{
event_id: "2",
time_stamp: "1377083342"
}
I see no errors here try this .. if it does not work past part of the json.
var json = JSON.parse(xmlHTTP.responseText),
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++){
message+="<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++){
message+="<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";
you don't need to write msg=msg+evntmsg it's confusing and leads to errors
also you don't need another var for events one is enough as you just append
so msg+=newstring
think o it as you just append a string.
tip.: cache your json.
var collection = JSON.parse(xmlHTTP.responseText).collection
for(var i=0 , co ; co = collection[i] ; ++i){
message+="<tr><td>" + co.customer.name + "</td>";
for(var j=0 , ev ; ev = co.events[j] ; ++j){
message+="<td>" + ev.time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";

Categories

Resources