Show values from query in a table using php and ajax - javascript

I have a problem with my code, So I have an array and I pass to template, the array is like this :
Array
(
[0] => Array
(
[ref_article] => 1903
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 14.00
[gifts_number] => 3
)
[1] => Array
(
[ref_article] => 1907
[ref_fournisseur] => sdsds
[lien_fournisseur] => www.four.com
[prix_ht] => 12.00
[gifts_number] => 1
)
)
Now in template I do :
for (var item in result) {
document.getElementById('order_information').setAttribute('class','display-on');
document.getElementById('order_information').setAttribute('class','table');
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>' + 'description' + '</td>'+
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>' + 'disponibilite' +
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").html(html);
console.log(result[item]['ref_article']);
}
The problem is that only the last <td></td> shows on the page, in this case only the article with [ref_article] = 1907. What am I doing wrong? Can you help me please? Thanks in advance

The issue is because you are using html() to add the content - this will overwrite any pre-existing content in the #content-order element. Instead, try using append():
$("#content-order").append(html);
Also note that you can amend your first two lines to use a jQuery selector and the addClass() method:
$('#order_information').addClass('display-on table');
If you want to clear information added from a previous request you can use .empty() before the for loop that appends new content. Here's a full example:
// $.ajax({...
success: function(result) {
$("#content-order").empty(); // remove existing content
$('#order_information').addClass('display-on table');
for (var item in result) {
var html = '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>'+
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
$("#content-order").append(html);
console.log(result[item]['ref_article']);
}
}

Try using this code
var html = '<table>';
for (var item in result) {
html += '<td>' + result[item]['ref_article'] + '</td>' +
'<td>' + result[item]['ref_fournisseur'] + '</td>' +
'<td>description</td>' + // removed redundant string concatenation
'<td>' + result[item]['lien_fournisseur'] + '</td>' +
'<td>' + result[item]['prix_ht'] + '</td>' +
'<td>disponibilite</td>' + // added missing </td>
'<td>' + result[item]['gifts_number'] + '</td>';
console.log(result[item]['ref_article']);
}
html += '</table>';
$("#content-order").html(html);

Related

How to loop through a json data from AWS dynamo db using javascript?

Pasting the GET api url on a browser shows me the json data. It looks like this:
{"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2}
But When I try to use ajax request to loop through the data, it returns [Object Object]. Please help me figureout this error.
Here is my frontend code:
$.ajax({
url: 'my URL goes here ...',
type: "GET",
success: function (data) {
alert('data fetched!');
var tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
// loop through data and display on table
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name + '</td>';
tr += '<td>' + Item.phone + '</td>';
tr += '<td>' + Item.email + '</td>';
tr += '<td>' + Item.date + '</td>';
tr += '<td>' + Item.time + '</td>';
tr += '<td>' + Item.desc + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
},
error: function () {
alert('fetch request failed!');
}
});
Here is the response on the page:
[Object Object] on each cell of each row.
As you can see, the value of each property is also an object: "name":{"S":""}
So you can write:
...
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
...
You are seeing object because you have an object inside it {"S": ""}. Either you need to convert your data in the required form or you need to use like Item.name.S everywhere.
const data = {"Count":2,"Items":[{"date":{"S":""},"time":{"S":""},"email":{"S":"test1#email.com"},"name":{"S":""},"phone":{"S":""},"desc":{"S":""}},{"date":{"S":"3/7/21"},"time":{"S":"8:00am - 9:00am"},"email":{"S":"binia#gmu.edu"},"name":{"S":"Bini A"},"phone":{"S":"1234567890"},"desc":{"S":"I like your cut G"}}],"ScannedCount":2};
let tr = '<tr><th>Full Name</th><th>Phone Number</th><th>Email</th><th>Requested Date</th><th>Requested Time</th><th>Customer Feedback</th></tr>'; // row
data.Items.forEach(function (Item) {
tr += '<tr><td>' + Item.name.S + '</td>';
tr += '<td>' + Item.phone.S + '</td>';
tr += '<td>' + Item.email.S + '</td>';
tr += '<td>' + Item.date.S + '</td>';
tr += '<td>' + Item.time.S + '</td>';
tr += '<td>' + Item.desc.S + '</td></tr>';
});
$('#createdHoursDb').append(tr); // update table
console.log(tr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="createdHoursDb">
</table>

Append <img> to <tbody> with JavaScript

I have an AJAX call, and on success, a HTML <img> element is appended to the tbody.
Here is the code:
for (var i = 0; i <= list.length - 1; i++) {
var patientsList = ' <td class="point">' +
(i+1) +
'</td>' +
'<td class="title"> ' +
list[i].dateOfBirthday +
'</td>' +
'<td class="title"> ' +
list[i].lastName +
'</td>' +
'<td class="title"> ' +
list[i].firstName +
'</td>' + '<td>' + '</td>'
+ '<td>' + '</td>'
+ '<td>' + '</td>'
+ '<td style="text-align:end;>' + ' <img src="~/images/doc 50.png" />'+ '</td>';
$("#patients").append('<tr>' + patientsList + '</tr>');
};
The problem is, the image does not appear in the table.
The path is correct.
Why is it not appending?
Path is not correct. Try ./ instead of ~/ .
Your image name contains whitespace: doc 50.png. Try to rename the file and replace the code with something like this:
<img src="./images/doc-50.png" />'
And if your images folder is at the same level as the file, which code you have provided, use ./, not ~/.

Predefined table head, add rows from array

I have a predefined table head like this:
<div class="container">
<div class="livsmedelsmall">
<h1>Sökning av livsmedel</h1>
<form class="form">
<div class="form-group">
<label for="livsmedelsSokOrd">Livsmedel</label>
<input type="search" class="form-control" id="livsmedelsSokOrd" placeholder="t ex makaroner">
</div>
<button type="button" class="btn btn-default" id="sok-button">Sök</button>
</form>
<table id="tabell" class="table">
<thead>
<tr>
<th>Livsmedel</th>
<th>Energi (kcal/100g)</th>
<th>Kolhydrater</th>
<th>Protein</th>
<th>Fett</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<br>
And I want to add content to it from an array using this code:
// Work with the response
success: function(response) {
console.log(response); // server response
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
// Itererar genom samtliga rader i resultatet
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
$('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'
+
'</tr>').appendTo(table);
$("#tabell").show;
});
}
However it does not work and I have no idea of why it doesn't!
Hope your ajax is successful & response is correct. If it is so then you may need to target tbody for appending the tr
You can try this snippet
var trElement = '';
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
trElement += $('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'+
'</tr>').
});
$('#tabell tbody').append(trElement)
Here the trElement variable is outside the each function. You can declare it inside the success function or as a separate variable.
Also dom manipulation is costly so, you can create a the complete object of tr(s) & append it at once.
Hope this will be useful
Try it...
// Work with the response
success: function(response) {
console.log(response); // server response
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
// Itererar genom samtliga rader i resultatet
$.each(livsmedelArray, function(i, livsmedelArray) {
// Skapar en tabellrad för varje apotek och hämtar ut respektive
// attribut för det aktuella apoteket och lägger in cellerna i tabellraden
$('<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'
+
'</tr>').appendTo("#tabell");
$("#tabell").show;
});
}
You should be appending to body..
try this
var table = $("#tabell tbody");
***************EDIT***************
I am not sure about the rest of your code so why don't you try this..
var block = "";
$.each(livsmedelArray, function(i, livsmedelArray) {
block+='<tr><td>' + livsmedelArray.namn + '</td>' +
'<td>' + livsmedelArray.energi + '</td>' +
'<td>' + livsmedelArray.kolhydrater + '</td>' +
'<td>' + livsmedelArray.protein + '</td>' +
'<td>' + livsmedelArray.fett + '</td>'+
'</tr>';
});
table.html(block);
In the script, we need to just replace only .appendTo(table); with .appendTo('table');
Either we can replace the above script with below mentioned script:
success: function (response) {
console.log(response);
var livsmedelArray = response.livsmedel;
var table = $("#tabell");
console.log(livsmedelArray);
$.each(livsmedelArray, function (i, livsmedelArray) {
$('<tr><td>' + livsmedelArray.namn + '</td>'
+ '<td>' + livsmedelArray.energi + '</td>'
+ '<td>' + livsmedelArray.kolhydrater + '</td>'
+ '<td>' + livsmedelArray.protein + '</td>'
+ '<td>' + livsmedelArray.fett + '</td>'
+ '</tr>').appendTo('table');
$("#tabell").show;
});
}

Javascript - return dynamic row data with checkbox input

I seem to only be able to find the answer to this problem in JQuery and I would really like a pure JS solution.
I have a dynamically generated table that I build from a parsed JSON file. I added a checkbox for each row. My question is, do I also have to generate a unique ID or Class for each cell? How can I return a variable containing the data from just the row selected?
var watchLog = new XMLHttpRequest();
var rowChecked;
watchLog.onreadystatechange = function () {
if(watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '"
onclick="function rowData(){if(this.checked){rowChecked = ' + status[i]["Load ID"] + '; return console.log(rowChecked);};">';
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
You can try something like
//use this to store the mapping of values, assuming loadid is unique for each record else a unique property of the record has to be used
var watchlogic = {};
var watchLog = new XMLHttpRequest();
watchLog.onreadystatechange = function () {
if (watchLog.readyState === 4) {
var status = JSON.parse(watchLog.responseText);
var watchLogCell = '';
for (var i = 0; i < status.length; i += 1) {
//store the record in watchlogic with key as the unique value
watchlogic[status[i]["Load ID"]] = status[i];
watchLogCell += '<tr>';
watchLogCell += '<th scope="row" class="rowHeader"><input type="checkbox" name="selectRow' + i + '" onclick="onSelect(this)" data-loadid="' + status[i]["Load ID"] + '">'; //store the current record's unique value in an attribute
watchLogCell += '<td>' + status[i]["Load ID"] + '</td>';
watchLogCell += '<td>' + status[i]["Carrier Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current PU Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Vendor Name"] + '</td>';
watchLogCell += '<td>' + status[i]["Original DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Current DO Date"] + '</td>';
watchLogCell += '<td>' + status[i]["Load Status"] + '</td>';
watchLogCell += '<td>' + status[i]["Truck Status"] + '</td>';
watchLogCell += '<td>' + status[i]["DA First"] + '</td>';
watchLogCell += '<td>' + status[i]["PO Number"] + '</td>';
watchLogCell += '<td>' + status[i]["Buyer No"] + '</td>';
watchLogCell += '<td>' + status[i]["Comments"] + '</td>'
watchLogCell += '</tr>';
}
document.getElementById('tableBody').innerHTML = watchLogCell;
}
};
watchLog.open('GET', 'watchlogic.json');
watchLog.send();
function onSelect(el) {
//here el is the clicked element then use the data attribute value to get the unique valeu of the record and use that to get the record form the watchlogic object
var status = watchlogic[el.dataset.loadid]; //or this.getAttribute('data-loadid') for <= IE10
console.log(status)
}

How to clone element when i use $.append

I have some data from json when page load i pull to my combo box.
function DataProvide(){
//Load data from json
selectValues = {
"pilih" : "-Pilih-",
"id" : "ID",
"emp_name" : "Employee Name",
"photo_path" : "Photo Path",
"emp_id" : "Employee ID",
"birth_place" : "Birth Place",
"birth_date" : "Birth Date"
};
$.each(selectValues, function(key, value) {
$('#data1_1')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
$(document).ready(function() {
DataProvide();
});
When the page is load, I successfully generated the data input into the combo box, but my problem is when I want to perform additional row in the table using $.Append....
$(".addCF").click(function(){
count += 1;
$("#customFields").append(
'<tr>'
+ '<td>'
+ '<select id="data1_'+count+'" class="tabelBaru" name="data1[]">'
+ '<option value="pilih" selected >Pilih</option>'
+ ... clone from element $('#data1_1')
+ ... clone from element $('#data1_1')
+ ... clone from element $('#data1_1')
+ '</select>'
+ '</td>'
+ '<td>'
+ '<input id="data2_'+count+'" type="text" name="data2[]" class="data2" value="" placeholder=""/>'
+ '</td>'
+ '<td>'
+ '<input id="data3_'+count+'" type="email" name="data3[]" class="data3" value="" placeholder=""/>'
+ '</td>'
+ '<td>'
+ 'Remove'
+ '</td>'
+ '</tr>'
);
});
How do I use the function $.clone to take $('#data1_1') element along with all data that was created when the first page is opened??
Try
$(".addCF").click(function () {
count += 1;
var $row = $('<tr>' + '<td>' + '</td>' + '<td>' + '<input id="data2_' + count + '" type="text" name="data2[]" class="data2" value="" placeholder=""/>' + '</td>' + '<td>' + '<input id="data3_' + count + '" type="email" name="data3[]" class="data3" value="" placeholder=""/>' + '</td>' + '<td>' + 'Remove' + '</td>' + '</tr>').appendTo("#customFields");
$row.find('td:first').append($('#data1_1').clone())
});
The following should do the trick:
var myHtml = ""
$.each(selectValues, function(key, value) {
myHtml += "<option value=\"" + key + "\">" + value + "</option>";
});
$("data1_1").append(myHtml);
Note that building it as a string, while it might not look as good is always more efficient.

Categories