Adding JSON data to table in AJAX - javascript

Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});

Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}

Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});

Related

How to fetch image form its path given in the csv file to create HTML table?

I wanted the HTML table to show a specific image from its path given in the file.
csv file:
HTML Page output:
HTML code which I'm currently using.
<script>
function arrayToTable(tableData) {
var Table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return Table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
I applied this script because every time I will have a variable number of rows and columns, but how to modify this script so that it will read the image address given in the col 3 and fetch those images from their path and put them in the table.
If the image is always going to be in the third column, you could do something like this.
i !== 0 is telling the browser to ignore the first row.
j === 2 is telling the browser to render the third column differently.
If the image won't always be in column 3 you could parse each string value and see if it is a image URL, but if this works it works.
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
});
function arrayToTable(tableData) {
var table = $("<table></table>");
$(tableData).each(function (i, rowData) {
var row = $("<tr></tr>");
$(rowData).each(function (j, cellData) {
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
row.append($("<td>" + cellData + "</td>"));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$("body").append(arrayToTable(Papa.parse(data).data));
}
});
give an id to your table:
var Table = $('<table id="my-table"></table>');
then create an image element with the address you already have in the cell:
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
Below you can run an example with sample data:
function arrayToTable(tableData) {
var table = $('<table id="my-table"></table>');
$(tableData).each(function(i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function(j, cellData) {
row.append($('<td>' + cellData + '</td>'));
});
table.append(row);
});
return table;
}
$('body').append(arrayToTable([["asdf","qwer","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"]]));
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Jquery ajax call inside another ajax call is not working as expected inside a for loop

I have an ajax call within a for loop which is inside another ajax call. The code is as follows:
$.ajax({
type: "GET",
url: URI, //URI
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json) {
var tr = '';
tr = tr + '<tr>';
for (var i = 0; i < Json.length; i++) {
debugger;
tr = tr + '<td>'
tr = tr + '<table><tr><td>'
tr = tr + '<div id="theDiv" class="DivClass">';
tr = tr + '<img id="btnEdit" onclick="EditLevelZeroValue(' + Json[i].ID + ')" src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:24px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-70px;">';
tr = tr + " <label id='LevelLbl' style='position:relative; z-index:2;top: 20px; color:white;'> " + Json[i].Title + " </label>";
tr = tr + " </div> ";
tr = tr + " </td> ";
tr = tr + "</tr> ";
var URI1 = OMSiteUrl + 'api/Levels/GetLevelOne?subModuleID=' + 1 + '&parentId=' + Json[i].ID;
debugger;
$.ajax({
type: "GET",
url: URI1, //URI
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json1) {
debugger;
for (var j = 0; j < Json1.length; j++) {
debugger;
if (Json1[j].Publish==true)
{
tr = tr + "<tr><td>";
tr = tr + '<div id="theDiv" Class="DivClass2">';
tr = tr + '<img src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:6px;margin-top:-40px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-35px;">';
tr = tr + " <label id='LevelLbl' class='font'style='margin-top:17%;margin-left:26%'> " + Json1[j].Title + "</label>";
tr = tr + "</td></tr>"
}
else
{
tr = tr + "<tr><td>";
tr = tr + '<div id="theDiv" Class="DivClassChange">';
tr = tr + '<img src="../Images/Edit-icon.png" title="Edit" alt="Smiley face" style="padding-left:6px;margin-top:-40px;"><img src="../Images/delete.gif" title="Delete" alt="Smiley face" style="margin-left:-17px;margin-bottom:-35px;">';
tr = tr + " <label id='LevelLbl' class='font'style='margin-top:17%;margin-left:26%'> " + Json1[j].Title + "</label>";
tr = tr + "</td></tr>"
}
}
},
error: function () { alert('error'); }
});
tr = tr + "</table>";
tr = tr + "</td>";
}
tr = tr + '</tr>';
$('#levelBox').html(tr);
//tr = tr + '</tr>';
//$('#levelBox').html(tr);
},
error: function () { alert('error'); }
});
I have a for loop inside first ajax call and inside that for loop i have ajax call for each iteration. I want the code to execute the following way:
First ajax call returns list of data, for each data I need to create a table and fetch another list of data and bind to the same table and for second iteration i need to create another table and fetch another list of data and bind it to the newly created table.
EXPECTED RESULT
Now whats happening is, first ajax call returns a list of data and for each data, tables are created. Later the other list of data is fetched and it binds it to one table alone.
If i make async as false, the result is as follows:
Async False results
Can someone help me?
You should use a closure
for (var i = 0; i < arr.length; i++) {
(function(i) {
// your stuff
})(i);
}
or $.each() which creates a closure for you
So in your case
for (var i = 0; i < Json.length; i++) {
(function(i) {
// your stuff
})(i);
}
Use async: false in the ajax call
$.ajax({
type: "GET",
url: URI1, //URI
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Json1) {
... // your code
}
});
The 'A' in AJAX stands for 'asynchronous' which means your looped AJAX calls will be fired sequentially. If you need to wait on your 'success' callback to complete before triggering the next request, you can set the 'async' option to false.
$.ajax({
async: false,
// ...
});

Set JSON values to HTML Table in Java Script?

function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert(response);
},
});
}
Im still working on it,
I print alert for output and got as below
[{
"userId":1,
"email":"santosh.jadi95#gmail.com",
"mobile":"9900082195",
"gender":"male",
"qualification":"1",
"dob":"2016-01-01",
"login":{
"loginId":1,
"userName":"santosh",
"password":"santosh",
"userType":"admin"
}
}]
I want the above JSON values in an HTML Table, is it Possible?
If yes, then i just want to know that, how it can be done?
Got the Solution,, Thank u all for the kind support
function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
var obj = JSON.parse(response);
$("#tableId").html("");
var tr+="<tr><th>User ID</th><th>User Name</th></tr>";
for (var i = 0; i < obj.length; i++){
tr+="<tr>";
tr+="<td>" + obj[i].userId + "</td>";
tr+="<td>" + obj[i].login.userName + "</td>";
tr+="</tr>";
}
$("#tableId").append(tr);
}
});
}
Yes it is possible. if you want to print json data in simple html table then just iterate (use loop) till your json length and construct your table inside loop.
But i will suggest you to use dataTable / bootstrap table plugin there you just need to pass json at the initialization time.
for Example,
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
You'd simple just create a for loop inside success as following:
the obj[i] down below is just a placeholder. You'd have to get the correct value you want to place there.
HTML table container:
<div id="tableContainer">
<table>
<tbody class="tableBody">
<tbody>
</table>
</div>
JSON to append to table:
function loadUserTable(userType)
{
var TableHTML = '';
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert("eeee: "+response);
var obj = JSON.parse(response);
for (i = 0; i < obj.length; i++)
{
TableHTML += '<tr><td>' + obj[i].userId + '</td></tr>';
}
},
});
$(".tableBody").append(TableHTML);
}

Display JSON result in Table Format

$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[i].die_no && data[i].status && data[i].location) {
txt += "<tr><td>"+data[i].die_no+"</td><td>"+data[i].status+"</td><td>"+data[i].location+"</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
Controller page
$die_no = array();
$status = array();
$location = array();
while ($row = mysql_fetch_array($query)) {
$die_no[] = $row["die_no"]; // or smth like $row["video_title"] for title
$status[] = $row["status"];
$location[] = $row["location"];
}
$res = array($die_no, $status, $location);
echo json_encode($res);
HTML page
<p>
<table id="table" class="hidden">
<tr>
<th>die_no</th>
<th>Status</th>
<th>Location</th>
</tr>
I would like to display result in HTML table format, so I have passed my result in array format to Json but the results are not displayed in HTML page.
I could see the response by using chrome Inspect element under network option . Please help me to display the retrieved results in HTML tabular format.
If you add console.log(data) in your succes response,you can see how the object is structured.
To access the desired json value you should try data['die_no'][i],data['status'][i],data['location'][i].
You can insert the response like this:
<table id="tbl">
</table>
Javascript:
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
$('$tbl').append("<tr><td>"+data['die_no'][i]+"</td><td>"+data['status'][i]+"</td><td>"+data['location'][i]+"</td></tr>");
}
}
}
}
}); //you missed this in your question
Use this
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[0][i] || data[1][i] || data[2][i]) {
txt += "<tr><td>" + data[0][i] + "</td><td>" + data[1][i] + "</td><td>" + data[2][i] + "</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
});
Actually your php code is not returning key value pair. So in your js you cannot use data.die_no etc
Use this like just I did:
data[0][i]
You have syntax error:
use
txt += <tr><td>
instead of
txt += tr><td>
after if condition

unable to bind click event to nested li in jquery

I have done a lot but nothing is working anymore, i would like to do when i click on td then it will take the id of that td and this id will go to the database and it will fetch all the childs of that id. now i want to append those childs to that td based on id. But when i click on the nested td it take the id of parent. Here is my code.
<script type="text/javascript" >
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("td").bind('click',function(e) {
e.stopPropagation();
which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("td[id='" + which_li +"']").append(res);
}
});
});
});
</script>
Html table with default id that will be the root of all the id :
<table id="data" style=" margin:0 auto; border:1px solid #ddd" >
<tr>
<td id='2'>2</td>
</tr>
</table>
it's working only once but after that it only taking the id of parent td not child td.
Please help me to short out this problem.
e.stopPropagation();
Stop Propagation is also not working anymore.
here is my sql table
create table user_login (
id int not null auto_increment,
parent int not null
);
my table structure would be like this :
// this is my table strucutre
<table id="data" >
<tr>
<td id="2">2
<table>
<tr>
<td id="24">24
<table>
<tr>
<td id="29">29</td>
<td id="30">30</td>
</tr>
</table>
</td>
<td id="25">25</td>
<td id="26">26</td>
</tr>
</table>
</td>
</tr>
</table>
when i will click on id 2 then a table will append to td containing childs 24,25,26 and when i will click on 24 then a table will append to td containing childs 29,30 and so on.
but when i want to get the id of 24 or 25 then it's giving me id of parent td that is 2 every time. Please help me.
You are binding, but only to elements that exist when you bind. The event propagates up until it hits an element that was bound, at which point it is stopping propagation. What you need to do is bind the event to an element that exists, and then delegate that event to the one's that may or may not exist yet. Something like this should work:
$("body").on('click', 'td', function(e) {
e.stopPropagation();
which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("td[id='" + which_li +"']").append(res);
}
});
});
Well first of all, you are not binding the click event to newly added td's.
Secondary, don't bind a click event to a tag, better give a class to a td, and bind the click to that class, this way you will have more flexibility.
Corrected your code a bit:
<script type = "text/javascript" >
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for (var i = 0; i < parts.length - 1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("#data").on('click', '.closed', function(e) {
var clicked_td = $(this);
$.ajax({
type: "POST",
data: {
id: clicked_td.attr("id")
},
cache: false,
url: t + "treeData",
success: function(data) {
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for (var i = 0; i < childs.length; i++) {
if (childs[i] != "") {
res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>"; //added a 'closed' class
}
}
res += "</tr></table>"
clicked_td.removeClass("closed").append(res); //removing the class, so the click event won't fire again
}
});
});
});
</script>
And your html (added a class to td):
<table id="data" style=" margin:0 auto; border:1px solid #ddd" >
<tr>
<td id='2' class='closed'>2</td>
</tr>
</table>
In the future, try to use dataType: 'json', and on your php side you can do something like:
...
$response = array('2', '3', '5', '10');
echo json_encode($response);
Using this method (and it is the right one if you takeajax seriously), you wond have to manually split the values, so instead of:
...
success: function(data) {
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for (var i = 0; i < childs.length; i++) {
if (childs[i] != "") {
res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>";
}
}
res += "</tr></table>"
clicked_td.removeClass("closed").append(res);
}
You can do this:
success: function(data) {
var res = "<table style='border:1px solid #ddd'><tr>";
$each(data, function()
res += "<td class='.closed' id='" + this + "'>" + this + "</td>";
});
res += "</tr></table>"
clicked_td.removeClass("closed").append(res);
}
Use live instead of bind if you want to bind to elements that might be added in the future since you are adding elements dynamically (http://api.jquery.com/live/) :
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("td").live('click',function(e) {
// snip
Also stopPropogation works fine.
Try
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("#data td:not(.child td)").bind('click',function(e) {
e.stopPropagation();
var which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table class='child' style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='child-"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("#" + which_li).append(res);
}
});
});
});

Categories

Resources