JSON information is looped once - javascript

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.

Related

Jquery append after ajax not working every time

I have a problem with jquery append. This is the code:
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
This code work very well, but not every time. (only the append option not working. This: console.log(string_option) it`s ok every time).
Can you help me, please?
Thank you!!
Looks like you need to put the code to be executed after the document is fully loaded using the "$( document ).ready" jQuery event
$( document ).ready(function() {
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
});
You can learn more about this on the below link
https://api.jquery.com/ready/
Try to check the response on Ajax success sometimes it happens due to malformed JSON is sent back with a 200/OK
One possible problem could be that you run the .append() before DOM is loaded. If this is the problem you can try 2 methods:
put this javascript code inside footer.
add to your code:
$(document).ready(function(){
//... your ajax request
})

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

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

How to load JSON data associated with each link onclick?

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.

how to add class and elements (<p>) to appended <li> in jQuery/JS

Im fairly new with jQuery, JS & AJAX so please bear with me.
I tried to create a dynamic that will generate its content based on the result in my DB. This is the HTML code i want to generate with jQuery/JS :
<li class="box">
<img class="picture" src="images/HotPromo/tagPhoto1.png"/>
<p class="name"><b>Name</b></p>
<p class="address">Address</p>
</li>
It a list item with a class and some HTML elements in it.
So i tried something like this :
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/"+keyword, //This is the current doc
type: "GET",
error : function(jq, st, err) {
alert(st + " : " + err);
},
success: function(result){
if(result.length == 0)
{
//temp
alert("not found");
}
else{
for(var i = 0; i < result.length; i++)
{
//generate <li>
$('#list').append('<li class="box">');
$('#list').append('<img class="picture" src="images/HotPromo/tagPhoto1.png"/>');
$('#list').append('<p class="name"><b>Name</b></p>');
$('#list').append('<p class="address">Address</p></li>');
}
var i=0;
//THIS PART IS ALREADY WORKING
$(".box").each(function(){
var name, address, picture = "";
if(i < result.length)
{
alert("generated");
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
i++;
});
}
}
});
The AJAX & CSS seems dont read the class="box".
I have done some research and trials, and i can do something like $('#list').append('<li>Back to top</li>'); easily. But i dont know why my code is not working.
Note : I have tried to manually code the HTML above, and the AJAX for generating data is already working. So it seems the only problem is the append now.
Any help is appreciated. Thanks :D
The .append() does not work as a string concatenate operation, you need to create a dom structure and pass it to the .append() call
Try
$('#list').append('<li class="box"><img class="picture" src="images/HotPromo/tagPhoto1.png"/><p class="name"><b>Name</b></p><p class="address">Address</p></li>');
But the code should be as simple as
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/"+keyword, //This is the current doc
type: "GET",
error : function(jq, st, err) {
alert(st + " : " + err);
},
success: function(result){
if (result.length == 0) {
// temp
alert("not found");
} else {
var $list = $('#list');
$.each(result, function(idx, item) {
$list.append('<li class="box box' + idx
+ '"><img class="picture" src="'
+ item.boxpicture
+ '"/><p class="name">' + item.name
+ '</p><p class="address">'
+ item.address + '</p></li>');
})
}
}
});

Categories