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);
}
});
}
Related
I using a code on my page. Like this:
$('#language_id').change(function () {
var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
$.each(response.archs, function() {
options += '<option value="' + this.arch_id + '">' + this.name + '</option>';
});
$('#arch_id').html('<option value="0">- ' + selachitecture + ' -</option>'+options);
$('#arch_id').attr('disabled', false);
}
});
});
$('#arch_id').change(function(){
var version_id = $('#version_id :selected').val();
$('#selectBoxInfo').load('https://example.com/dl.php?fileName=' + arch_id + "&lang=" + lang);
return(false);
});
$('body').on('click', '.buttond a', function() {
alert("new link clicked!");
$("a").removeAttr("onclick");
});
I explain my code: when selecting an optional, it will create a button "Download". This button load by Ajax. I don't want feature pop-up of this button.
So, I tried to prevent this button turn on the pop-up.
The problem is: at first click in button, my Javascript is not working. It only works from the second click.
I don't know problem at here. I using 'on' to listen to all event.
replace your code with this code ..
$('#selectBoxInfo')
.load('https://example.com/dl.php?fileName=' + arch_id+"&lang="+lang
,function(){
$("a").removeAttr("onclick");
}
);
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>');
}
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.
I'm using select2 4.0 and when I load data from a json file none of the created elements fire the select2:select event. I thought it would have something to do with event delegation, but the examples on the website seem to do just fine.
I've been breaking my head over this for the past hour and I just don't understand what I'm missing.
Right now I'm using this to select an item, but that obviously doesn't work:
$("body").on("click", "#select2-select-results .person-entry", function()
{
var $this = $(this);
var name = $this.data('name');
select2.find('option').val(name).text(name);
});
Binding $(...).on('select2:select'); never fires, but $(...).on('select2:open); does. So I'm not sure what's going on.
What I did notice however, is when the data has been loaded, no <option> tags are created.
This is my entire JavaScript that's handling the thing:
(function($)
{
"use strict";
var term = null;
var select2 = $("#select");
select2.select2({
allowClear: true,
ajax: {
url: "js/data.json",
dataType: "json",
delay: 250,
data: function(params)
{
// Save the terms for filtering
term = params.term;
return params;
},
processResults: function(data)
{
var people = [];
for(var i = 0; i < data.people.length; i++)
{
var person = data.people[i];
var filter = term || '';
if (person.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1) {
people.push(person);
}
}
return {
results: people
};
}
},
templateResult: function(person)
{
if (person.loading) {
return person.text;
}
var personDetails = '<div class="person-information">' +
'<span class="person-name">' + person.name + '</span>' +
'<span class="person-address">' + person.address + '</span>' +
'</div>';
return '<div class="person-entry" data-name="' + person.name + '"><img src="' + person.image + '" />' + personDetails + '</div>';
},
templateSelection: function(person)
{
return person.name;
},
escapeMarkup: function(markup)
{
return markup
}
});
$("body").on("click", "#select2-select-results .person-entry", function()
{
var $this = $(this);
var name = $this.data('name');
select2.find('option').val(name).text(name);
});
})(jQuery);
Can someone tell me what I'm doing wrong here? I just don't get it.
It sounds like you are not setting the id field on your data objects. Without this field, Select2 cannot know what to set the value of your <select> to, so it doesn't allow it to be selected.
Additionally, the text field is required for searching and (by default) displaying the data in the results list.
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.