Long back I used JSON and was successful to get the hash tag feeds from twitter and facebook. But presently I am just able to get the feeds but its not being updated constantly that means it not been update dynamically. I guess I need to ajaxify it, but I am not able to do that since I am not aware of ajax. Here is the code which I have used to get the twitter search feeds.
$(document).ready(function()
{
$("#Enter").click(function(event){
var searchTerm = $("#search").val() ;
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data)
{
$("#tweets").empty();
if(data.results.length < 1)
$('#tweets').html("No results JOINEVENTUS");
$.each(data.results, function()
{
$('<div align="justify"></div>')
.hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span><a href="http://www.twitter.com/'
+ this.from_user + '">' + this.from_user
+ '</a> ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
});
});
function makeLink(text)
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
The code below should help you. What I've done is moved the code which fetches the tweets into a function. This function is then called every X seconds to update the box. When the user enters a new search term and clicks "Enter", it will reset the timer.
var fetchSeconds = 30; //Number of seconds between each update
var timeout; //The variable which holds the timeout
$(document).ready(function() {
$("#Enter").click(function(event){
//Clear old timeout
clearTimeout(timeout);
//Fetch initial tweets
fetchTweets();
});
});
function fetchTweets() {
//Setup to fetch every X seconds
timeout = setTimeout('fetchTweets()',(fetchSeconds * 1000));
var searchTerm = $("#search").val();
var baseUrl = "http://search.twitter.com/search.json?q=%23";
$.getJSON(baseUrl + searchTerm + "&rpp=1500&callback=?", function(data) {
$("#tweets").empty();
if (data.results.length < 1) {
$('#tweets').html("No results JOINEVENTUS");
}
$.each(data.results, function() {
$('<div align="justify"></div>').hide()
.append('<hr> <img src="' + this.profile_image_url + '" width="40px" /> ')
.append('<span>' + this.from_user + ' ' + makeLink(this.text) + '</span>')
.appendTo('#tweets')
.fadeIn(800);
});
});
}
function makeLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
Hope this helps
Related
The Problem
I'm trying to figure out how to return HTML that I've built from a JSON file with jQuery.
I seem to have gotten returnLocations() to wait until getLocations() is finished so that the variable locationsBody is finalized with information gathered from my .each loop. The trouble (I think) is my not being able to return that variable to output it to my HTML page.
The Question
How can I return the variable locationsBody?
Note
(there may be errors in the below code as I trimmed it down as best I could but I think it should illustrate the problem with or without them)
The jQuery
the global variables
var locationsFull = 'un d fined';
var locationsOpener = '' +
'<div class="locations-header">places youve been</div>' +
'<div class="locations-container">' +
'<div class="locations-nav left">left</div>' +
'<div class="locations-nav right">right</div>'
;
var locationsBody = '<div class="locations-inner">'; // opening of container
var locationsCloser = '</div>'; // closing of container
the function
function locationsFunction() {
function getLocations() {
var wait = $.Deferred();
var area = 'Area1';
var counter = 1;
$.getJSON("locations.json", function(data) {
$(data.places).each(function() {
var location = this.location;
var image = this.image;
if (this.area === 'Area1') {
if (counter == 2) {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div></div>'
;
counter = 0; // added closing of container, reset to 0
} else {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div>'
;
counter = counter + 1;
}
}
})
wait.resolve();
})
return wait;
}
function returnLocations() {
locationsFull = locationsOpener + locationsBody + locationsCloser; // works, proven in alert and console.log
//alert(locationsFull); // works
console.log(locationsFull); // works
//return locationsFull; // doesnt work
//return 'anything'; // doesnt work
}
getLocations().then(returnLocations);
}
the call
$(function() {
$('.locations-body').html(locationsFunction());
})
The JSON File
{"places":[
{
"area": "Area1",
"location": "Downtown",
"image": "downtown.jpg"
},
{
"area": "Area1",
"location": "Uptown",
"image": "uptown.jpg"
}
]}
The HTML
<div class="locations-body"></div>
Further Note: Questions similar to this have been asked dozens of times on stackoverflow alone and those questions and answers have hundreds of thousands of reads. I have read through all of the top ones and more over the last 2 days. My problem is my inability to thoroughly understand the answers and apply them to my exact situation as seems to be the problem of the dozens (hundreds/thousands?) of people asking these questions and the hundreds of thousands (millions?) of people that have been searching for solutions to asynchronous problems.
You could just call .html() inside the returnLocations() function if that's viable.
the function
function returnLocations() {
locationsFull = locationsOpener + locationsBody + locationsCloser;
$('.locations-body').html(locationsFull);
}
the call
$(function() {
locationsFunction();
}
Otherwise you'll need to look into callbacks, read this, if you need to do it this way I can update my answer with an example later on.
Have you tried
return wait.promise();
instead of returning the Deferred?
Then calling like this:
var deferredChain = $.Deferred();
deferredChain.then(getLocations).then(returnLocations);
deferredChain.resolve();
I discovered today that simply putting a .done at the end of $.getJSON seems to work just the same and is much easier than using $.Deferred and the associated lines of code to make it work.
function locationsFunction() {
var area = 'Area1';
var counter = 1;
$.getJSON("locations.json", function(data) {
$(data.places).each(function() {
var location = this.location;
var image = this.image;
if (this.area === 'Area1') {
if (counter == 2) {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div></div>'
;
counter = 0; // added closing of container, reset to 0
} else {
locationsBody = locationsBody +
'<div class="locations-places">' +
'<img src="images/places/' + image + '">' +
'<div class="locations-places-image">' + location + '</div>' +
'</div>'
;
counter = counter + 1;
}
}
})
}).done(function() {
locationsFull = locationsOpener + locationsBody + locationsCloser;
$('.locations-body').html(locationsFull);
});
}
I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
var apiKey = '';
var url = '';
var data;
// console.log(position);
$.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {
$('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
$('.js-current-item2').html(data.currently.summary);
gif(data.currently.icon)
city(position.coords.latitude + "," + position.coords.longitude)
});
}
And here is the function for pulling images from GIPHY
function gif(status) {
var apiKey = '';
var url = 'http://api.giphy.com/v1/gifs/search?q=';
var query = status;
$.getJSON(url + query + apiKey, function(data) {
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
});
}
In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');
I've been following this answer in an attempt to write good asynchronous js - but I can't quite figure out what's going wrong for me.
I'm using autocomplete to request a specific set of files from the server, but for some datasets these files may not exist (i.e, there may be one, or up to four files). If they do exist, I want to append .html to include them.
The images don't load unless I add
async: false
to the .ajax call, which makes the callback redundant.
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
$.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
})(i);
}
Then image_html contains html for only those images that exist.
$('#outputcontent').html(outer_html + image_html + outer_html_end);
Can anyone explain to my misunderstanding here please? Why isn't image_html being populated?
EDIT: 'full' code below. I use jquery autocomplete to pull from the stellar_comp array, then for those with properties that exist (some are blank), html is generated. Within that is the ajax call.
$(function () {
var stellar_comp = [
{
value:'X0005-28',
data: {
set0: {
aperture:'X2105-28',
secat:'X025-18',
set:'1',
run:'r06',
continuumFilter:'J',
narrowBandFilter:'638/28',
numberOfSources:'1',
priorityCode:'1'
etc... etc ...
},
},
];
$('#autocomplete').autocomplete({
lookup: stellar_comp,
onSelect: function (suggestion) {
var path_Value = 'data/' + suggestion.value + '/';
var outer_html = '<h1>' + suggestion.value + ' </h1> <div class="container">';
var outer_html_end = '</div>';
for (var category in suggestion.data) {
if (suggestion.data.hasOwnProperty(category)) {
if (suggestion.data[category].aperture) {
summary_table_contents = '<tr> <td>' + suggestion.data[category].set + '</td> <td>' + suggestion.data[category].run + '</td> <td>' + suggestion.data[category].continuumFilter + '</td> <td>' + suggestion.data[category].narrowBandFilter + '</td> <td>' + suggestion.data[category].numberOfSources + '</td> <td>' + suggestion.data[category].priorityCode + '</td></tr> ';
summary_table += summary_table_contents;
var aperturePlot = suggestion.data[category].aperture + '_' + suggestion.data[category].run;
var seCATPlot = suggestion.data[category].secat + '_Rsub_ss_' + suggestion.data[category].run;
var aperture_match = suggestion.data[category].aperture_match;
cog = path_Plots + aperturePlot + '_cog';
sbprof = path_Plots + aperturePlot + '_sbprof';
thumb_cog = '';
thumb_cog_temp = '';
thumb_sb = '';
temp='';
for (var i = 1; i < 5; i++) {
(function (counter) {
function some_function(callback) {
$.ajax({
type: "GET",
url: cog + counter + "_1.jpg",
async: false,
success: function (result) {
callback(counter);
}
});
}
some_function(function (num) {
var thumb_cog_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + cog + num + '_1.jpg"> <img class="img-thumbnail" src="' + cog + num + '_4.jpg" /></a> <div class="caption"><h5>' + suggestion.value + ':S' + num + '</h5></div></div>';
var thumb_sb_temp = '<div class="col-lg-3 col-sm-4 col-xs-6"> <a class="thumbnail" target="_blank" href="' + sbprof + num + '_1.jpg"><img class="img-thumbnail" src="' + sbprof + num + '_4.jpg" /></a><div class="caption"><h5>' + suggestion.value + ':S' + num + ' </h5></div></div>';
console.log(num, counter);
thumb_cog += thumb_cog_temp;
thumb_sb += thumb_sb_temp;
});
})(i);
}
cog_sbprofile_row='<div class="row"><h3>C o G</h3> ' + thumb_cog + '</div><div class="row"><h3>Profiles</h3> ' + thumb_sb + '</div>';
console.log(cog_sbprofile_row);
body_html += aperture_row;
body_html += seCAT_row;
body_html += aperture_match_row;
body_html += pixel_map_row;
body_html += skyprofile_row;
body_html += cog_sbprofile_row;
body_html += '<hr>';
};
};
};
top_html += summary_table + '</tbody> </table> </div></div> <hr>';
$('#outputcontent').html(outer_html + hipass_container + top_html + body_html + outer_html_end);
}
});
});
The current problem is due to using the resulting HTML string, before it has been created via multiple asynchronous calls. You need to either defer that operation until all loads are completed, or change the situation so it is not dependent on final completion (progressive loading looks busier anyway).
Personally I would simply insert placeholders for the images as you loop and insert each as they load. This way the order is retained. You can even do effects (fade etc) on each as they load:
var wrapper = "";
for (var i = 1; i < 5; i++) {
// Make a placeholder element for each image we expect
wrapper += '<div class="thumbnail" id="thumb_' + i + '">'
(function (num) {
// call the function
$.ajax({
type: "GET",
url: num + "_1.jpg",
success: function (result) {
var image_temp = '<img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num;
// Insert new image into unique element and fade it in
$('#thumb_'+num).append(image_temp).fadeIn();
}
});
})(i);
}
// Append all placeholders immediately - these will be appended to as each image is loaded
$('#outputcontent').html(outer_html + wrappers + outer_html_end);
Update:
As Alnitak points out, the whole exercise is a little pointless as you are ignoring the result returned from the Ajax call anyway, so you might as well drop the Ajax call (which adds no value) and simply build the image elements on the fly server-side :)
You have to do the appending after all ajax requests finish their jobs. First define this:
var after = function(reqs) {
var d = $.Deferred(),
cnt = reqs.length;
if (!cnt) {
d.resolve();
}
var limit = cnt; // separate var just in case reqs are synchronous
// so it won't mess up the loop
for (var i = 0; i < limit; i++) {
reqs[i].always(function() {
cnt--;
if (!cnt) {
d.resolve();
}
});
}
return d.promise();
};
You can use $.when instead of this but if one of the requests results in 404 it won't wait for others. Now:
var image_html = "",
requests = [];
for (var i = 1; i < 5; i++) {
(function (counter) {
// define function with the callback argument
function ajaxTest(callback) {
return $.ajax({
type: "GET",
url: counter + "_1.jpg",
success: function (result) {
callback(counter);
}
});
}
// call the function
var req = ajaxTest(function (num) {
var image_temp = '<div class="thumbnail"> <img class="img-thumbnail" src="'+ num + '_1.jpg" /> Image' + num + '</div>';
console.log(image_temp); //check readout
image_html += image_temp;
});
requests.push(req); // push the request to the array
})(i);
}
after(requests).done(function() {
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
Note that I've added return $.ajax(...).
BTW: what's the point of defining ajaxTest function? Just put everything in an anonymous callback.
Read more about deferred objects and promises here:
http://api.jquery.com/category/deferred-object/
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
or just google it.
EDIT: if the order is important then you just have to tweak the callback function a bit:
var image_html = []; // array instead of string
// some code...
var req = ajaxTest(function (num) {
// ...
image_html[counter] = image_temp;
});
// some code...
after(requests).done(function() {
image_html = image_html.join("");
$('#outputcontent').html(outer_html + image_html + outer_html_end);
});
Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});
Im beginner in AJAX & JS so please bear with me.
I use this AJAX for the pagination :
$(function () {
var keyword = window.localStorage.getItem("keyword");
//pagination
var limit = 3;
var page = 0;
var offset = 0;
$("#btnLoad").on('click', function () {
page++;
if (page != 0)
offset = (page - 1) * limit;
$.ajax({
url: "http://localhost/jwmws/index.php/jwm/search/msmall/" + keyword + "/" + limit + "/" + offset, //This is the current doc
type: "GET",
error: function (jq, st, err) {
alert(st + " : " + err);
},
success: function (result) {
alert("offset=" + offset + " page =" + page);
//generate search result
$('#search').append('<p style="float:left;">Search for : ' + keyword + '</p>' + '<br/>' + '<p>Found ' + result.length + ' results</p>');
if (result.length == 0) {
//temp
alert("not found");
} else {
for (var i = 0; i < result.length; i++) {
//generate <li>
$('#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><p class="hidden"></p></li>');
}
var i = 0;
$(".box").each(function () {
var name, address, picture, id = "";
if (i < result.length) {
name = result[i].name;
address = result[i].address;
picture = result[i].boxpicture;
id = result[i].mallid;
}
$(this).find(".name").html(name);
$(this).find(".address").html(address);
$(this).find(".picture").attr("src", picture);
$(this).find(".hidden").html(id);
i++;
});
$(".box").click(function () {
//alert($('.hidden', this).html());
window.localStorage.setItem("id", $('.hidden', this).html());
$("#pagePort").load("pages/MallDetail.html", function () {});
});
}
}
});
}).trigger('click');
});
Please notice that i use the variables for pagination in the url:. I tried to alert the page and offset variable, and its working fine.
However, the AJAX only working for the first page (when page load). The rest is not working even though the page and offset variable's value is true.
Theres no warning/error in console. The data just not shown.
Any help is appreciated, Thanks :D
It is a bit hard to debug your code when the whole HTML is missing.
Could you put your code into JSFiddle, both HTML and JS.