I want to append data I fetched from server to a div tag, but I can't get it to work. That's HTML with a div tag to which I'd like to append data from the JS code.
HTML:
<body onload="initialize()">
<div id="text"></div>
</body>
And here is JavaScript code. I would like to replace document.write with a function that will append data to a div tag.
JS:
function initialize() {
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
document.write('<img src="' + data[i].image + '" />' + data[i].title + data[i].description + '<br>');
}
});
}
Fiddle: http://jsfiddle.net/GDxtf/
I just started learning JavaScript. Help will be greatly appreciated :)
Paste this code in the bottom of your HTML document, right before </body>:
<script>
// If you're not using an HTML5 doctype, use <script type="text/javascript> instead of just <script>
$(function () {
$targetDiv = $("#text");
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
var $div = $("<div />");
var $img = $("<img />");
$img.attr("src", data[i].image);
$img.appendTo($div);
var $title = $("<h2>" + data[i].title + "</h2>");
$title.appendTo($div);
var $description = $("<p>" + data[i].description + "</p>");
$description.appendTo($div);
$div.appendTo($targetDiv);
}
});
});
</script>
Did this solve your problem?
Related
When I load this page to the browser the Javascript shows up but the HTML (H1 tag) doesn't. I haven't been able to figure out why I cant get HTML to show up on the page. Im new to both Javascript and HTML...clearly.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
</head>
<body>
<h1>hello</h1>
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
You are removing the <h1> tag when you clear the inner HTML of the body tag by calling $('body').html(''). Why don't you work in a different container element that you can clear:
<body>
<h1>Hello, world!</h1>
<div id="root"></div>
<script>
$(document).ready(function(){
var $root = $('#root');
// $root.html(''); // Already empty. Don't need to clear it.
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($root);
index -= 1;
}
});
</script>
</body>
As #charlietfl said, $body.html(''); clears all previous html content of the body tag. More simply it just replaces the contents with what is inside the quotes, or in this case nothing.
Here is documentation on the subject:
JQuery html() Documentation
EDIT:
Inspired by Sean's answer,
If you want to use the body container directly you can do so like this:
<body>
<h1>Hello, world!</h1>
<script>
$(document).ready(function(){
var $body = $('body');
// $body.html(''); // This clears it and since you don't want to, you shouldn't run this command.
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
</body>
I have an img_urls array which contains 2 image urls.
I use this array to loop img tag and using for loop.
But instead of having 2 images, i have 3 images in my output.
This is my code;
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
So, whats is wrong with my code?
JSFIDDLE
When adding the first image you generate a new div.
Then the second image if appended to existing divs.
You should have only one destination div. Add an id to the main div:
<div id="container"></div>
--
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
You need to use selector i.e. id class in the main div as when the next iteration occurs it contains two div in the body. Check this fiddle
Problem is that you have $("div") as selector. So when you append the first image, you also add new div. So the next image is appended to two divs. Probably you can add id to your div, so
<div id="test"></div>
...
$("#test").append
Reason is you are appending everything inside the loop.
$(function() {
var img_urls = ["url1", "url2"];
var html= ""
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>";
}
$("div").append(html);
});
You are appending to global div element, you are appending div also, so generated html will append to generated div too.
Here is html,
<div class='test'></div>
Here is javascript code,
$(function() {
var img_urls = ["image_url1", "image_url2"];
var html = '';
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>"
}
$("div.test").append(html);
});
Please find here working link here
I hope this will help
<div id="container"></div>
for (var i = 0; i < img_urls.length; i++) {
console.log(img_urls.length)
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
when you append the first image you create a div in that div the horse is added and the first div is also populated by the horse
Try this and see Demo
<div></div>
$(function() {
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<img src=' " + img_urls[i] + "'/> </br>"
);
}
});
I started new project and I use jquery to add content to article
when I create a slider with this code:
$(".inserttabtext1").click(function () {
var count = parseInt($(".firsttabtextcount").attr("name"), 10);
var name = parseInt($(this).attr("name"));
var id = "#" + name;
var idi,idt,content,idic,idtc;
content = "<div class='short-tabs'><ul>";
for (var i = 1; i <= count; i++)
{
idi = "#ftti" + i;
idic = $(idi).val();
if (i == 1)
{
content += "<li class='active'><a href='#'> " + i + idic + "</a></li>";
}
else
{
content += "<li><a href='#'> "+ i + idic +"</a></li>";
}
}
content += "</ul>";
for (var i = 1; i <= count; i++)
{
if (i==1)
{
content += "<div class='active'>";
}
else
{
content += "<div>";
}
idt = "#fttt" +i;
idtc = $(idt).val();
content += "<p class='text-go-center'>"+idtc+"</p></div>";
}
content += "</div>";
$(id).html(content);
});
and put them into html code my text slider not worked
but when I put manual html code in my page it work
I use these code for copy my html code
$(id).html(content);
$(id).append(content);
where is my wrong?
create a function and put your slider codes inside it, then call it in $(document).ready, and call it again after adding html
$(document).ready(function(){
Init();
});
function Init(){
//Call your slide function here
}
call Init after Adding Html
$(id).html(content);
$(id).append(content);
Init();
I've searched around and found no pure js solution to my issue that I can apply to my code.
It's a script that prints an array of images, but for now it only prints 1 array.
Pertinent code in html:
<div id="imgViewer"></div>
<script>
var imgViewerImages = ['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
</script>
<script src="services/imgViewer.js"></script>
And in JS:
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerImages.toString();
for (var i=0;i<imgViewerImages.length;i++){
imgViewerTarget.innerHTML = '<img src="' + imgViewerImages[i] + '">';
}
}
window.onload = imgViewerPrinter();
I'm still a noob is JS so I ask for your pacience.
Thanks in advance
try :
imgViewerTarget.innerHTML += "<img src="' + imgViewerImages[i] + '">";
If you want to print out an array of images shouldnt you have your HTML code in the loop making i the image number for example;
for (var i=0;i<imgViewerImages.length;i++){
var imgViewerImages = ['img/imgViewer/' + [i] + '.png'];
}
Try this optimized soln.
var imgViewerImages =['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
function imgViewerPrinter(){
var imgList=[];
for (var i=0;i<imgViewerImages.length;i++){
imgList.push('<img src="' + imgViewerImages[i] + '" />');
}
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerTarget.innerHTML = imgList.join('');
}
window.onload = imgViewerPrinter();
try something like this,Because your code rewrite innerHTML again and again, so you get last iterated value.
Instead of manipulating DOM in every loop,Below code will manipulate your DOM one time only.
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
var imgViewerImages_length = imgViewerImages.length;
var image = '';
for (var i=0;i<imgViewerImages_length;i++){
image += '<img src="' + imgViewerImages[i] + '">';
}
imgViewerTarget.innerHTML = image;
}
I'm a beginner at javascript/jquery and completely new to API's and I'm wondering if anyone could help me with something
What I'm trying to achieve is to have a user enter a keyword/phrase into a textbox, they click search and the page returns a list of people who have that word in their tweet.
I have so far been able to display results from a hard-coded keyword (which I got from a website) but when trying to change it I am getting nothing back.
Here is the working one with hard code
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('http://search.twitter.com/search.json?q=earthquake&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
</script>
<h2>Twitter</h2>
<div class="content">
</div>
And here is the code I'm working on now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
var button= document.getElementById('searchTwitter');
button.onclick= function(){
var text = document.getElementById('search').value;
}
var baseUrl = "http://search.twitter.com/search";
var query = document.getElementById('<%=searchTwitter.ClientID%>').value;
$(document).ready(function () {
$.ajax({
url: baseUrl + '&text' + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
});
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
}
</script>
<asp:TextBox ID="search" runat="server"></asp:TextBox>
<asp:Button ID="searchTwitter" runat="server" Text="Button" />
Any help would be much appreciated as I have been trying to find a way to do this for days.
thanks a lot
Here's a working example of what you are describing: http://jsfiddle.net/ZEjey/. You should be able to adapt it to your ASP code.
Relevant code below.
JQuery
$("#SearchButton").click(function() {
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
HTML
<h2>Twitter</h2>
Search for: <input id="TextSearch" type="text" /> <input type="button" id="SearchButton" value="Go" />
<div class="content"></div>
---
EDIT 0
Okay, the code below works. The <asp:Button automatically causes a postback so you don't see anything ever get loaded. You either need to use <input type="button" ... instead or stop the normal events from occurring using event.preventDefault(); as I did below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Twitter</h2>
<asp:TextBox id="TextSearch" runat ="server"/>
<asp:Button id="SearchButton" runat="server" Text="Search"/>
<div class="content"></div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script>
$(document).ready(function () {
$("#SearchButton").click(function () {
event.preventDefault(); // ADD THIS LINE TO YOUR CODE
$('.content').html("<em>loading...<em>");
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#" + data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
$('.content').html(html);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
});
</script>
</form>
</body>
</html>
It looks like you're making an ajax request on document ready, rather than when the button is clicked. I also don't see where you're adding the value from the text box to the query. Here's how you could change your code:
//this code will run when the page loads and set up the button so the
//onclick event executes your function
$(document).ready(function () {
var button = document.getElementById('<%=searchTwitter.ClientID%>');
//you need to make the ajax request in this function, because this
//is fired when the search button is clicked
button.onclick = function() {
var text = document.getElementById('search').value;
var baseUrl = "http://search.twitter.com/search.json";
var query = document.getElementById('<%=search.ClientID%>').value;
$.ajax({
//you're building the request url here, with the text from the
//box as the q parameter
url: baseUrl + '?q=' + query + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
};
});
//this function can be defined outside ready()
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
//I'm assuming you have a div with a content class on your page
$('.content').html(html);
}
You might also want to try out the Chrome developer tools (or Firebug in Firefox). You can set breakpoints and see what's happening at each step. You can also see what requests have been sent and the data returned. That will help give you a better handle on what's going on.