Display data in Div from json in jquery - javascript

I have data in a json using ajax code. Now I want to display data in a div Below is the code which I bring
{
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
}
and the div.
<div id="dvTable">
</div>
And for bringing the data below is the code.
function SearchInfo() {
var textBoxValue = $('#addresSearch').val();
$.ajax({
type: "POST",
url: "http://localhost:11181/Search/GetFilterSearch",
data: JSON.stringify({ textBoxValue: textBoxValue }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
// display data in div here
}
})
}
Now how should I display that data which is in json in a div and show it.

You can loop like:
$(document).ready(function(){
/*
var r = {
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
};
*/
//Empty rows
var r = {
"Table":[]
};
var html = '';
//Check if has data
if ( r.Table.length !== 0 ) {
html += '<table>';
for ( var key in r.Table ) {
var row = r.Table[key];
//For the header
if ( key == 0 ) {
html += '<tr>';
for ( var key2 in row ) {
html += '<th>';
html += key2;
html += '</th>';
}
html += '</tr>';
}
html += '<tr>';
for ( var key2 in row ) {
html += '<td>';
html += row[key2];
html += '</td>';
}
html += '</tr>';
}
html += '</table>';
} else {
//No data.
html += "No data.";
}
$( "#dvTable" ).html( html );
//console.log();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="dvTable"></div>

var table = $('#table_id');
for (i = 1; i < data.length; i++) {
table.append('<tr>');
table.find('tr:last-child').append(
'<td>' + data[i]["APP_MST_ID"] + '</td>',
'<td>' + data[i]["APPLICATIONNAME"] + '</td>'
);
}
<table class="GeneratedTable" align="center" id = "table_id">
<tr>
<th>APP_MST_ID</th>
<th>APPLICATIONNAME</th>
</tr>
</table>

This is one of a lot of possible answers. You can do it even with Object.keys, concatenating with DOM functions...
let response = {
"Table":[
{
"APP_MST_ID":321.0,
"APPLICATIONNAME":"R-Locator for Enterprise",
"PROJECTNO":"R4G-25-APD-006",
"VSS_FOLDER_LOC":null,
"CAT_ID":1.0,
"SPOC_APPUSRID":79.0,
"SUPPORT_TEAM":"0",
"REQUESTED_BY_APPUSRID":51.0,
"DELIVERY_MANAGER_APPUSRID":43.0,
"CREATEDBY_APPUSRID":null,
"CREATEDDATE":null,
"MODIFIEDBY_APPUSRID":null,
"MODIFIED_DATE":null,
"APPIMAGEPATH":null,
"PARENT_APP_ID":null,
"SERVER_LOCATION":null,
"USAGE_CATID":null
}
]
}
for(let k in response.Table[0]){
window.document.getElementById("dvTable").innerHTML+=`<div>${response.Table[0][k]}</div>`;
}
<div id="dvTable">
</div>

This could be a possible solution.
var json = '{"Table": [{"APP_MST_ID": 321.0,"APPLICATIONNAME": "R-Locator for Enterprise","PROJECTNO": "R4G-25-APD-006","VSS_FOLDER_LOC":null,"CAT_ID":1.0,"SPOC_APPUSRID":79.0,"SUPPORT_TEAM":"0","REQUESTED_BY_APPUSRID":51.0,"DELIVERY_MANAGER_APPUSRID":43.0,"CREATEDBY_APPUSRID": null,"CREATEDDATE": null,"MODIFIEDBY_APPUSRID": null,"MODIFIED_DATE": null,"APPIMAGEPATH": null,"PARENT_APP_ID": null,"SERVER_LOCATION": null,"USAGE_CATID": null}]}';
var objects = JSON.parse(json); // Parse the json
objects = objects.Table; // Get the content of Table
var string = ""; // create a string
jQuery.each(objects[0], function(id, value) { // get all the id's and values
string = string + value + " "; // Do something here with the values or id's
});
// create something where you add it, or do it inside the each()-function
var div = document.createElement('div');
div.innerHTML = string;
document.body.appendChild(div);
// ^ just to show the values in this example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You could just dump your formatted data to the div but as its difficult to replicate an $.ajax call I have commented out those parts.
It would work something like this:
var r =
`{
"Table": [{
"APP_MST_ID": 321.0,
"APPLICATIONNAME": "R-Locator for Enterprise",
"PROJECTNO": "R4G-25-APD-006",
"VSS_FOLDER_LOC": null,
"CAT_ID": 1.0,
"SPOC_APPUSRID": 79.0,
"SUPPORT_TEAM": "0",
"REQUESTED_BY_APPUSRID": 51.0,
"DELIVERY_MANAGER_APPUSRID": 43.0,
"CREATEDBY_APPUSRID": null,
"CREATEDDATE": null,
"MODIFIEDBY_APPUSRID": null,
"MODIFIED_DATE": null,
"APPIMAGEPATH": null,
"PARENT_APP_ID": null,
"SERVER_LOCATION": null,
"USAGE_CATID": null
}]
}`;
function SearchInfo() {
//var textBoxValue = $('#addresSearch').val();
//$.ajax({
// type: "POST",
// url: "http://localhost:11181/Search/GetFilterSearch",
// data: JSON.stringify({
// textBoxValue: textBoxValue
// }),
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function(r) {
// display data in div here
$("#dvTable").html("<pre>" + r + "</pre>")
// }
//})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="SearchInfo();">Search</button>
<div id="dvTable"></div>
If you are looking for an actual table then this is how you would do it:
var r = {
"Table": [{
"APP_MST_ID": 321.0,
"APPLICATIONNAME": "R-Locator for Enterprise",
"PROJECTNO": "R4G-25-APD-006",
"VSS_FOLDER_LOC": null,
"CAT_ID": 1.0,
"SPOC_APPUSRID": 79.0,
"SUPPORT_TEAM": "0",
"REQUESTED_BY_APPUSRID": 51.0,
"DELIVERY_MANAGER_APPUSRID": 43.0,
"CREATEDBY_APPUSRID": null,
"CREATEDDATE": null,
"MODIFIEDBY_APPUSRID": null,
"MODIFIED_DATE": null,
"APPIMAGEPATH": null,
"PARENT_APP_ID": null,
"SERVER_LOCATION": null,
"USAGE_CATID": null
}]
};
function SearchInfo() {
//var textBoxValue = $('#addresSearch').val();
//$.ajax({
// type: "POST",
// url: "http://localhost:11181/Search/GetFilterSearch",
// data: JSON.stringify({
// textBoxValue: textBoxValue
// }),
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function(r) {
// display data in div here
$("#dvTable").html(CreateTable(r).html())
// }
//})
}
function CreateTable(data) {
var data = data.Table;
var table = $("<table><tr /></table>");
$.each(data[0], function(key, value) {
table.find("tr").append("<th>" + key + "</th>");
});
$.each(data, function() {
var trHtml = $("<tr />");
$.each(this, function(key, value) {
trHtml.append("<td>" + value + "</td>");
});
table.append(trHtml);
});
return table;
}
th,
td {
border: solid 1px black;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="SearchInfo();">Search</button>
<div id="dvTable"></div>

There are multiple ways, one of them is put a table tag in your div and append rows in it, like:
$.each(r,function(index,value){
var html = '<td>'+
'<tr>'+value.APP_MST_ID+'</tr>'+
'<tr>'+value.APPLICATIONNAME+'</tr>'+
'<tr>'+value.PROJECTNO+'</tr>'+
'<tr>'+value.VSS_FOLDER_LOC+'</tr>'+
'<tr>'+value.CAT_ID+'</tr>'+
'<tr>'+value.SPOC_APPUSRID+'</tr>'+
'<tr>'+value.SUPPORT_TEAM+'</tr>'+
'<tr>'+value.REQUESTED_BY_APPUSRID+'</tr>'+
'<tr>'+value.DELIVERY_MANAGER_APPUSRID+'</tr>'+
'<tr>'+value.CREATEDBY_APPUSRID+'</tr>'+
'<tr>'+value.CREATEDDATE+'</tr>'+
'<tr>'+value.MODIFIEDBY_APPUSRID+'</tr>'+
'<tr>'+value.MODIFIED_DATE+'</tr>'+
'<tr>'+value.APPIMAGEPATH+'</tr>'+
'<tr>'+value.PARENT_APP_ID+'</tr>'+
'<tr>'+value.value.SERVER_LOCATION+'</tr>'+
'<tr>'+value.USAGE_CATID+'</tr>'+
'</td>'
$('#table_id').append(html);
})
and so on. and you can data format as you want.

Related

Ajax search with pagination.js and/or PHP

I want to do a search that can be triggered by given a specific URL (I tried with ajax and javascript here but im happy with a php variant also). I have 2 requirement phases (both should be displayed with pagination.js):
When I access eg.: https://<.myDomain.>/search/234x15 to put
the value inside the input and the filter automatically or make the
search over the whole database.
When I would go to eg.: https://<.myDomain.>/search I want to make POST search over the whole database.
My general problem is that I cannot include MySQL or other databases, I am limited to either JSON or objects/arrays (JS/php).
With my current solution processing 900 items using a big JSON file gets me a response after 5-8 seconds which is too long. And I will need to fill in with at least 3500 items.
Here is the solution I made:
<script>
var currentKeywords = $(location).attr('pathname');
var currentKeywordsFiltered = currentKeywords.replaceAll('+',' ');
const toBeSearched = currentKeywordsFiltered.split('/')[2];
$('#search-input').attr('value', toBeSearched);
var myArray = <?php echo json_encode($products_merged) ?>;
$(document).ready(function(){
console.log('Url keyword: ', toBeSearched);
var data = searchTable(toBeSearched, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$('#search-input').on('keyup', function(){
var value = $(this).val();
console.log('value: ', value);
var data = searchTable(value, myArray);
buildTable(data);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: data,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading data from db...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
});
$(function(){
if(toBeSearched === undefined){
buildTable(myArray);
(function(name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: myArray,
locator: 'dataSource',
totalNumber: 50,
pageSize: 20,
showPageNumbers: true,
showPrevious: true,
showNext: true,
showNavigator: true,
showFirstOnEllipsisShow: true,
showLastOnEllipsisShow: true,
ajax: {
beforeSend: function() {
container.prev().html('Loading...');
}
},
callback: function(response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '';
$.each(response, function (index, dataSource) {
dataHtml +=
'<div style="border: 1px solid #888888; border-radius: 5px; margin: 15px;" class="col-md-2">'
+ '<div class="card-body">'
+ '<b>'+ dataSource.title +'</b></h5>'
+ 'Vezi specificatii'
+ '</div>'
+ '</div>';
});
dataHtml += '';
container.prev().html(dataHtml);
}
})
})('demo');
}
});
function searchTable(value, data){
var filteredData = [];
for(var i = 0; i < data.length; i++){
value = value.toLowerCase();
var name = data[i].title.toLowerCase();
if(name.includes(value)){
filteredData.push(data[i])
}
}
return filteredData;
}
function buildTable(data){
var table = document.getElementById('myTable');
table.innerHTML = '';
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].title}</td>
<td></td>
<td></td>
</tr>`;
table.innerHTML += row;
}
};
</script>
My question would be which architectural solutions i could go towards or how can I improve my code so it can be more efficient.
PS: I tried doing it first with php submission by grabbing the url and I was ending up in infinite loop using header on processing page.

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);
}

Update html table according to ajax json response

i have a JSON response like below
{
"Parent": "skystar",
"Children": [
{"Name":"MW"},
{"Name":"PR"},
{"Name":"PV"},
{"Name":"ST"}
]
},
{
"Parent": "RR",
"Children": [
{"Name":"RC"},
{"Name":"RP"}
]
}
Now i need to bind this to the table.
i tried to call AJAX like below
$.ajax({
url: 'echo/sample.json/',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.Children + '</td>';
});
$('#records_table').append(trHTML);
}
});
But i am not able to bind the table
what i am doing wrong??
JSFIDDLE
one more thing every children has hypher link how to add it
How to do that in Jquery or javascript??
Any help??
Demo: http://jsfiddle.net/tqyn3/336/
var jsonData = '[{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}]';
$.ajax({
url: '/echo/json/',
type: 'POST',
data: {
json: jsonData
},
dataType:'json',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
//alert(item.children);
$.each(item.Children, function(j, child) {
trHTML += '<tr><td>' + child.Name + '</td>';
});
});
$('#records_table').append(trHTML);
}
});
Please see following JSFiddle http://jsfiddle.net/s701aduz/
var jsonData = '[{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}]';
$.ajax({
url: '/echo/json/',
type: 'POST',
data: {
json: jsonData
},
dataType:'json',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr>';
$.each(item.Children, function(j, child) {
trHTML += '<tr><td>' + child.Name + '</td>';
});
trHTML += '</tr>';
});
$('#records_table').append(trHTML);
}
});
The problem you had was that item.Children was an array itself so when you included that in the string it would simply output [object Object], you have to iterate over the children as well. Also make a row for each element in the response and a td for each child, or at least I'm guessing that's what you were intending.
var json_data = $.parseJSON(response);
var table = $('<table>');
$.each(json_data,function(index,obj){
var tr = $('<tr>');
$.each(obj.Children,function(_index,_children){
var td = $('<td>');
$(td).text(_children.Name);
$(tr).append(td);
})
$('#records_table').append(tr);
});
var jsonData = [{"Parent":"skystar","Children":[{"Name":"MW"},{"Name":"PR"},{"Name":"PV"},{"Name":"ST"}]},
{"Parent":"RR","Children":[{"Name":"RV"},{"Name":"RP"}]}
];
$.each(jsonData, function (i, item) {
if(i == 0) {
$('#records_table').find('th:first').html(item.Parent);
} else {
$('#records_table').find('th:last').after('<th>'+ item.Parent +'</th>');
}
$.each(item.Children, function(j, child){
if(i==0) {
var tr = $('<tr />');
var td = $('<td />');
$(td).text(child.Name);
$(tr).append(td);
$('#records_table').append( tr );
} else {
var td = $('<td />');
$(td).text(child.Name);
$('#records_table').find('tr:eq('+(j+1)+')').append( td );
}
})
});
Check it will help you
http://jsfiddle.net/tqyn3/338/

Adding JSON data to table in AJAX

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);
}
})
}
});

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