Combining AJAX/JSON call with iScroll - json

I am making a list form my JQM site from JSON data and are having no trouble with this. Now I want to add iScroll to the scene and if I use static list it works just fine, but when I get the list from JSON it won't fetch how many li I have and I can not scroll down to the bottom if I have lets say 20 li. I dont know how to combine my javascript so here is what i got so far [EDIT]:
var myScroll;
$(document).on('pageshow', function (){
var userid=1,
dataUrl = 'http://duefmun.dk/html5data/playermenu.php?callback=?&userid=' + userid,
dataCallback = function (data) {
var content = [];
$.each(data, function (i, val) {
content.push(val.list);
});
$('#games').html(content.join('')).listview('refresh');
},
fetchData = function () {
myScroll = new iScroll('wrapper');
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
});
Hope this makes sense and any help is appreciated :-)
EDIT: I have edited the post with something I think should be right but it is still not working? Please help :-/

My suggestion is that you should create iScroll after you get your data. So, your code should be:
...
fetchData = function () {
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
myScroll = new iScroll('wrapper');
...

Related

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

Using Spotify webAPI to play random album of artist (ID)

here is my "little" project, as I am not a developer myself please don't blame me for my stupid questions.
I want to create a "audio book machine".
I want to use a Website, that shows several Artists of audiobooks. If I click on one artist, a random audiobook of the clicked artist should be played.
I had a look at this code example: http://jsfiddle.net/qlmhuge/t7a1sh4u/
// find template and compile it
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/artists/61qDotnjM0jnY5lkfOP7ve/albums/',
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: 'artist:' + query,
type: 'album',
market: "DE"
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
results.addEventListener('click', function(e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingCssClass);
});
});
}
}
});
searchAlbums('TKKG');
but I cannot figure out how to change it to play a random album by one artist.
The artist will be defindes by the spotify ID so that the artist ist the correct one.
Can someone help me out with my problem? What else info is needed to complete my goal?
I would be very thankful if one can give me a hint, or whatever, to get to the right direction.
Best regards,
goeste
You have to modify your fetchTracks function here:
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
jsFiddle link
I got a little closer to the finish line... well, I guess:
I found the following on GitHub:
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
// credentials are optional
// var spotifyApi = new SpotifyWebApi({
// clientId : '',
// clientSecret : '',
// redirectUri : ''
// });
// Get albums by a certain artist
spotifyApi.getArtistAlbums('3meJIgRw7YleJrmbpbJK6S')
.then(function(data) {
console.log('Artist albums', data.body);
}, function(err) {
console.error(err);
});
However, I only get 20 albums out of 35. I need to increase the limit. The max limit is 50, as I read on the developer site of Spotify. As I only need to get one out of the 35 albums (randomly), how can I implement the randomize function and also play function in order to work?
I am still figuring out how to create a link from the results to show on a website with node.js.
Best regards, and thank you in advance for any assistance/help!
-goeste

Integrating tabletop.js with d3.js?

I want to reference a google spreadsheet using tabletop for for the data in my d3 visualization. The best solution I can come up with is this, but I know that it's not quite right.
window.onload = function() { init() };
var public_spreadsheet_url = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html';
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } )
}
d3.json("showInfo", function(data) {
console.log(data);
});
The data comes as an array already (see output below); and so there is no need to apply d3.json. You can start using the array for your d3 visualization right away.
window.onload = function() { init() };
var public_spreadsheet_url = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html";
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(rows) {
console.log(rows);
// build your d3 vis here..
}

knockout js polling not working

I am having difficulty with knockout refreshing.
Here's my viewModel;
$(document).ready(function () {
ko.applyBindings(new Task(), document.getElementById('taskSummary'));
setInterval(Task, 2000);
});
function task(name, description, project) {
var self = this;
self.name= ko.observable(name);
self.description = ko.observable(description);
self.project = ko.observable(project);
}
function Task() {
var self = this;
self.tasks = ko.observableArray([]);
self.tasks.removeAll;
$.getJSON("/api/tasks/5", function (data) {
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
It returns data to the view but does not update when I change the data in the back end database.
any help appreciated. Im sure its something small that I'm missing.
For knockout, it might be better if you apply your model to a new Task instance, save that instance, then set up a setInterval loop that can modify the Task's "tasks" observableArray values.
$(document).ready(function () {
var oTask = new Task();
ko.applyBindings(oTask, document.getElementById('taskSummary'));
function onLoop() {
var self = oTask;
$.getJSON("/api/tasks/5", function (data) {
self.tasks.removeAll(); // not sure if you need this...
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
setInterval(onLoop, 2000);
});

Twitter Bootstrap Row Filter / Search Box

I'm having trouble finding a tutorial on how to create a simple search query, or row filter, for Twitter Bootstrap. I've tried many, I'm not sure if I'm doing something wrong or the plugins are not compatible with Bootstrap. Please help if you can.
I've tried:
$(document).ready(function() {
//Declare the custom selector 'containsIgnoreCase'.
$.expr[':'].containsIgnoreCase = function(n,i,m){
return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
$("#search").keyup(function(){
$("#tabela").find("tr").hide();
var data = this.value.split(" ");
var jo = $("#tabela").find("tr");
$.each(data, function(i, v){
//Use the new containsIgnoreCase function instead
jo = jo.filter("*:containsIgnoreCase('"+v+"')");
});
jo.show();
}).focus(function(){
this.value="";
$(this).css({"color":"black"});
$(this).unbind('focus');
}).css({"color":"#C0C0C0"});
});
Nothing with this... Maybe I'm missing any "id" on my table or search box, I'm new with this.
Here's what I use:
$('input.filter').live('keyup', function() {
var rex = new RegExp($(this).val(), 'i');
$('.searchable tr').hide();
$('.searchable tr').filter(function() {
return rex.test($(this).text());
}).show();
});
To use it, you just create a table, with a tbody with the class "searchable" and then an input with class "filter" somewhere on your page (I prefer to put them in a Bootstrap Popup behind a search icon).
This is live example of solution provided by Filipp Lepalaan. Many thanks for this small and perfect code.
Example
$(document).ready(function () {
(function ($) {
$('#filter').keyup(function () {
var rex = new RegExp($(this).val(), 'i');
$('.searchable tr').hide();
$('.searchable tr').filter(function () {
return rex.test($(this).text());
}).show();
})
}(jQuery));
});