JQuery AJAX is not inserting HTML? - javascript

ajax working with the simple javascript but not with the jquery
Here is the code
$(document).ready(function (){
var url = 'data.json';
$.getJSON(url, function(response){
var htm = '<ul class="bulleted">';
$.each(response, function(index, value){
htm += '<li>';
htm += value.name;
htm += value.inoffice;
htm += '</li>';
});
htm += '</ul>';
$("container").html(htm);
});
});
The problem is nothing is added in the container div.

Without being able to see your HTML, my guess would be that you've done your jQuery selector wrong when fetching your container.
$("container") will select all <container></container> elements.
$("#containter") will select <div id="container"></div> element.
$(".container") will select all <div class="container"></div> elements.
Currently, you're using the first selector but that will only work if the element in your HTML is a <container>. If it's just a typo and you have an ID or a class, use one of the other selectors instead.

Related

slideToggle() doesn't push elements created with jquery append() down

I do have a problem using slideToggle(). The following DOM elements won't be pushed down, they just overlap. I tried a lot of versions. I do create the tags with jquery getting a JSON from which I fill in the tag content, so I iterate over the JSON to create the HTML tags for each element :
var project_infos = '';
jQuery(document).ready(function(){
$.getJSON('project.json', function(data){
project_infos += '<div class=\"row\">'
+ '<div class=\"span3\">'
+ '<div class=\"well\">'
+ '<div>'
+'<ul class=\"nav nav-list sidebar-list\">';
for( var i = 0; i < data.length; i ++ ) {
var project_name = data[i]["item"];
project_infos += '<li>'
+'<label class=\"tree-toggler nav-header\">'
+'<i class=\"fa fa-arrow-right\"></i>' + project_name + '</label>'
+'<ul class=\"nav nav-list tree\">'
+'<li><label class=\"tree-toggler nav-header\">Katalogue</label></li>'
+'<li>'
+'<ul class=\"nav nav-list tree\">'
+'<li>Link</li>'
+'<li>Link</li>'
+'<li>Link</li>'
+'</ul>'
+'</li>'
+'<li><label class=\"tree-toggler nav-header\">History</label></li>'
+'<li><label class=\"tree-toggler nav-header\">Whole project</label></li>'
+'</ul>'
+'</li>';
}
project_infos += '</ul></div></div></div></div>';
$('#tree').append(project_infos);
$('.tree-toggler').click(function () {
$(this).parent().children('ul.tree').slideToggle('slow');
});
});
});
EDIT : screenshot of html output.
screenshot html output
Thanks in advance!
Use
find() instead of children()
$(this).parent().find('ul.tree').slideToggle('slow');
children() will only search for first level child elements.
I just reset all css styles for my div and finally it worked. I already defined styles for the sidebar and for the ul and li tags. One of the styles was the problem. It kept the elements from toggle down in the sidebar.
Thanks for your time!

How to properly generate HTML in a JavaScript widget?

I've been following this tutorial on how to make JS widget. However I noticed that manually building html with plain JavaScript is not DRY. I am planning to build a form, tables etc. in a JS widget. Whats the best way to do this?
$.getJSON(jsonp_url, function(data) {
var fruits = ["Apples", "Mangoes", "Banana"];
var myHtml = "<ul>";
$(fruits).each(function(i){
myHtml += "<li>" + fruits[i] + "</li>";
});
myHtml += "</ul>";
$('#example-widget-container').html(myHtml);
});
if you want one of your divs or containers to continuously grow while you build dynamic content, without losing older content, use jQuery.append
$('#example-widget-container').append(myHtml);
this is probably the cleanest way. Or you can do other things like
var html = $('#example-widget-container').html();
newHtml = yourContent;
$('#example-widget-container').html(html + newHtml);
In JavaScript you can generate html content in different ways :
Create HTML with a string directly :
$("#sampleArea").append('<div class="' + newClass + '">' + newText + '</div>');
Create HTML with jQuery Api wrapping :
$("#sampleArea").append($('<div/>',{class : newClass}).text(newText));
Use a template engine in Javascript (like mustache.js) :
<script id="exampleTpl" type="x-tmpl-mustache">
<div class="{{class}}">{{text}}</div>
</script>
<script>
var data = {
class: newClass,
text: newText
}
var template = $('#exampleTpl').html();
var html = Mustache.render(template, data);
$('#sampleArea').append(html);
</script>
The best solution will depends of your use.

Adding html while iterating over jquery object

Is there a better way of inserting somewhat complex html into a page other than the way I'm doing now? :
function display(friends) {
$(".row").empty();
$.each(friends, function(index, friend) {
var html = '<div class="profileImage" style="float:left;padding:20px; width:200px">';
html += '<a href="/app/click/' + friend.id + '">';
html += '<img id="' + friend.id + ' " src="https://graph.facebook.com/' + friend.id + '/picture?width=200&height=200 " />';
html += '</a>';
html += '</div>';
$(".row").append(html);
});
Currently I have a list of facebook friends which are styled nicely. When a user searches through the friends, the entire content block is emptied and the result is appended (i'm using autocomplete). However the design could change and get more complex so i'm looking for a scalable way of doing what I have above.
Instead of creating the html inside the javascript, is there a smarter way of doing this? Perhaps with $.load() and passing each friend as an argument? But that seems very slow and server intensive if you have to list 100 friends.
One good way to go would be to use a templating engine, handlebars (as mentioned in the prev answer) is one of them. You could create your own as well if your scenario is simple as this. And another key thing is not to use append inside the loop, instead construct them to a temp array and add it to the DOM in the end. If your list is big and appending to the dom in the array can be expensive.
Add the template html with a placeholder for friendId
<script type="text/html" id="template">
<div class = "profileImage" style = "float:left;padding:20px; width:200px">
<a href = "/app/click/{{friendId}}">
<img id = "{{friendId}}" src = "https://graph.facebook.com/{{friendId}}/picture?width=200&height=200 " />
</a>
</div>
</script>
And
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = [];
$.each(friends, function (index, friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
rows.push(templateHtml);
});
$row.html(rows); //Append them in the end
}
Demo
You could use $.map as well.
var $template = $('#template'),
$row = $('.row');
function display(friends) {
var rows = $.map(friends, function (friend) {
var templateHtml = $template.text().replace(/{{friendId}}/g, friend.id);
return templateHtml;
});
$row.html(rows);
}
A scalable solution would be to use a template engine and make the server returns JSON response.
Take a look at Handlebars.js http://handlebarsjs.com/

how to get data from hyperlink in html

I'm stuck trying to retreive categories id from a hyperlink in HTML5. First I have parsed a JSON link in HTML5 using jQuery.
My code:
HTML code:
jquery code:
<script src="jquery-1.8.3.min.js"></script>
<script>
$.getJSON('http://' '/storejson.php', function(data) {
var output="<ul>";
for (var i in data.items) {
output += "<li>" + data.items[i].categories_name + " " "</li>";
}
output += "</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
HTML code:
<div id="placeholder" align="justify">
I have given a hyperlink to placeholder like above. Categories are shown by parsing JSON but I want to show subcategories through hyperlink. So please tell me how can I acheive this?
What you could do is get the href from the a tag by
then pass link to your getjson when clicked or however best suits you and that will send the request to the php file, but keep in mind your php file has to also be set up to grab parameters passed in the url string from the href.
<script>
var link;
$("a").click(function(){link = $(this).attr("href")}); // get this inside a click event on the 'a' tag
alert(link);// to see the url being passed
$.getJSON(link, function(data) {
var output="<ul>";
for (var i in data.items) {
output += "<li>" + data.items[i].categories_name + " " "</li>";
}
output += "</ul>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
CLICK // If you click here it should send the href data

jquery .find and append img tag

I am trying to load pictures name from a xml object and append to div. I am getting confuse with append typing layout, not able to find where im doing typing mistake.
This is working
$("#nn").append("<img id='theImg' src='/pic/jas/pic1.jpg'/>");
This not working
$("#nn").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
My jquery script part is
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var pic_infoVar = xml.find("pic_info");
pic_infoVar.each(function () {
var customer = $(this);
$("#picDiv").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
});
$("#loader").hide();
}
Html Div tag
<div id="picDiv">
LoadPic
</div>
Provded that pic_name is infact an element in an XML data structure (ex: <pic_name>pic1.jpg</pic_name>), the code that will do what you want is:
$("#nn").append("<img id='theImg' src='/pic/jas/" + customer.find("pic_name").text() + "'/>");
This is how i used to do
document.getElementById('nn').innerHTML +='<img src="'+customer.find(\"pic_name\")+'"/>';

Categories