How to load JSON data associated with each link onclick? - javascript

I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>

The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});

Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.

Related

how to display JSON Array into table using AJAX in JSP

I am new to ajax. I am trying to display data into table in JSP file.
API is called using AJAX.
Controller pass below response:
BatchwiseStudent [name=Ram, course=MCA (Commerce), emailId=rammansawala#gmail.com, placed=null, batch=2016, mobileNo=7.276339096E9]
In JSP page:
<script type="text/javascript">
function getStudentDetails(){
$batch = $('#batch');
$course = $('#course');
$.ajax({
type: "GET",
url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),
success: function(data){
console.log("SUCCESS ", data);
if(data!=null){
$("#batchwiseTable").find("tr:gt(0)").remove();
var batchwiseTable = $("#batchwiseTable");
$.each(JSON.parse(data),function(key,value){
console.log(key + ":" + value);
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['name']);
rowNew.children().eq(2).text(value['emailId']);
rowNew.children().eq(3).text(value['placed']);
rowNew.children().eq(4).text(value['batch']);
rowNew.children().eq(5).text(value['mobileNo']);
rowNew.appendTo(batchwiseTable);
});
$("#batchwiseTable").show();
}
},
error: function(e){
console.log("ERROR ", e);
}
});
}
</script>
I can see new row into the table but there is no data. I want name, emaild, mobileNo, etc into particular field.
can anyone guide me where am i wrong?
Below code should be keep in the .jsp Page where you show table you don;t need to write html code for table jsp page.
<div id="insert-table-here"></div>
Javascript code:
below code is for ajax call
replace uri with your url value that is used in your url.
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
var str = '<table class="table table-bordered"><thead>'+
'<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
$.each(data, function (key, value) {
str = str + '<tr><td>' +
value.name + '</td><td>' +
value.course + '</td><td>' +
value.emailId + '</td><td>' +
value.placed + '</td><td>' +
value.batch + '</td><td>' +
value.mobileNo + '</td></tr>';
});
str = str + '</tbody></table>';
$('#insert-table-here').html(str);
}, error: function (data) {
}, complete: function (data) {
}
});

how to dynamically create a dropdown menu?

I have no problem creating the menu dynamically.
My problem : the class submenu is not working. I assume it's because the alert doesn't appear.
When I hard code the li´s and do not create them dynamically, the submenu works.
I'm using .NET
<script type="text/javascript">
jQuery(document).ready(function () {
mostrarGrupo01();
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
});
function mostrarGrupo01()
{
var k = 0;
var grupo01;
$.ajax({
type: "POST",
url: "Mesa.aspx/getGrupo01",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
grupo01 = response.d;
$('#grupos').empty();
$.each(grupo01, function (index, BEGrupo) {
//var r = $('<input type="button" value="' + BEAreaCC.DSAREACC + '" id="' + BEAreaCC.CDAREACC + '" name="' + BEAreaCC.CDAREACC + '" style="font-size:xx-large" onclick="botonClick(this.id, this.name, this.title);"/> ');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '" onclick="mostrarGrupo02(this.name, this.id);">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
//var t = $('<li class="submenu"><button type="button" name="' + BEGrupo.CDGRUPO01 + '">' + BEGrupo.DSGRUPO01 + ' </button> <ul></ul> </li>');
var t = $('<li class="submenu">' + BEGrupo.DSGRUPO01 + '</li>');
$('#grupos').append(t);
k++;
});
},
failure: function (msg) {
$('#grupos').text(msg);
}
});
}
</script>
HTML :
<div class="contenedorMenu">
<nav class="menu">
<ul id="grupos">
</ul>
</nav>
</div>
The HTML element with class submenu is added to your page dynamically. You therefore need to bind your event in the following way:
$(".submenu").on('click',function () {
alert("hola");
$(this).children("ul").slideToggle();
});
You are binding the click event before .submenu is added to the DOM due to the asynchronous nature of $.ajax.
You have two options:
1 . Bind you click event within the .ajax success callback after you add the .submenu elements to the DOM
success: function (response) {
...
$.each(grupo01, function (index, BEGrupo) {
...
});
$(".submenu").click(function () {
alert("hola");
$(this).children("ul").slideToggle();
})
},
2. Or change your click binding to target the parent ul
$("#grupos").on('click', '.submenu', function () {
alert("hola");
$(this).children("ul").slideToggle();
})

String Not Appended to Dynamically Created Div

I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}

JSON information is looped once

So the problem is that I'm loading JSON files from url into my html and it's working perfectly besides for the fact that it shows the information twice..
Does anyone know why this is the case?
Here's the Jquery/Javascript code that I use to load the JSON into my html.
$.ajax({
url: 'http://datatank4.gent.be//bevolking/totaalaantalinwoners.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
i = 0;
var access;
var url;
$(data).each(function(index, value) {
wijkname = value.wijk;
year = value.year_2010;
i++;
$('#pagewrap2').append(
'<div class="dataond col col-xxs-12 col-md-3"> <h2> ' + wijkname + '</h2><p>' + year + '<div id="maps">' + "<iframe width='100%' height='100%' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q="+ encodeURIComponent( wijkname + ' ' + 'Gent' ) +"&output=embed'></iframe>" + '</div>' + '</p></div>'
);
});
}
});
First check the response of this ajax call.
If the response look fine maybe you're making the ajax call twice.
For example when you add an event listener twice. (add off() function before click() if you're using jquery)
I've found the problem. Really stupid but I linked my file twice in my index.html...
Thanks everyone for your replies.
<script type="text/javascript">
$(document).ready(function() {
var categoriesId = [];
$.getJSON("http://datatank4.gent.be//bevolking/totaalaantalinwoners.json", function(data) {
$.each(data, function(index, item) {
categoriesId.push(item.wijk);
}
);
for (i = 0; i < categoriesId.length; i++) {
alert(categoriesId[i]);
var newInProductPriceDiv = document.createElement('div');
newInProductPriceDiv.setAttribute('id', "recentlyViewedProductPriceDiv" + i);
newInProductPriceDiv.setAttribute('class', "subcategoryListPriceDiv");
newInProductPriceDiv.innerHTML = newInProductPriceDiv.innerHTML + categoriesId[i];
document.getElementById('pagewrap2' + i).appendChild(newInProductPriceDiv);
}
}
);
}
);
</script>
if you have any confusion then tell me ok . and if you not get your exactly output then also tell me.

All Dynamic Posts defaults to first Object

I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position

Categories