I am trying to get a *.srt file and parse it with this script: Parse a SRT file with jQuery Javascript.
I've got a problem with the AJAX call blocking rest of the JS code. I tried to add syncs, set timeout, I wrapped it into a setTimeout function, tried with another *.srt file, but still it's not working. It doesn't throw error, it alerts end dialog, parsed lines are stored in variable but another scripts are frozen.
var subtitles = [];
$.ajax({
method: "GET",
url: '{% static "file.srt" %}',
async: true,
error: function(data) {
alert("error");
},
success: function(data) {
function strip(s) {
return s.replace(/^\s+|\s+$/g, "");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
for (s in srt_) {
st = srt_[s].split('\n');
if (st.length >= 2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if (st.length > 2) {
for (j = 3; j < st.length; j++)
t += '\n' + st[j];
}
//define variable type as Object
subtitles[cont] = {};
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
document.body.innerHTML += " (" + subtitles[cont].start + " - " + subtitles[cont].end + " ) " + subtitles[cont].text + "<br>";
}
cont++;
}
alert("end");
},
timeout: 2000,
});
Please help me.
Related
I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
for (i = 0; i < data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if (data.d.results[i]['Name'] != null) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>
I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>
I have a code to put two cameras on my site:
$(document).ready(function(){
var m;
var index;
var IP;
var port;
var name;
var user;
var password;
var image_old;
var image_new;
var cameraFeed;
var topImage;
var urls = [];
$.ajax({
type: "GET",
url: "json.htm?type=cameras",
dataType: "JSON",
async : false,
success: function(data) {
for(m=0; m<=1; m++){
index = data.result[m].idx;
IP = data.result[m].Address;
port = data.result[m].Port;
name = data.result[m].Name;
user = data.result[m].Username;
password = data.result[m].Password;
image_old = data.result[m].ImageURL;
image_new = image_old.replace("#USERNAME", user).replace("#PASSWORD", password);
cameraFeed = "http://" + IP + ":" + port + "/" + image_new;
alert(cameraFeed + m);
urls.push(cameraFeed);
}
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
},
error: function(data) {
alert("Error")
}
});
});
And html code:
<img id="topImage0" width="640px">
<img id="topImage1" width="640px">
I can not create a script to make setinterval work for both imgs. It works only for one of them. Any suggestions how to make it works ?
Set interval works only for one img.
To give you an idea how to structure your application code:
Get the data from the server
Create the URLs from data
Update each image every X milliseconds with those URLs
In code:
$.ajax({...}).done(function(data) { // get data from server
// create URLs
var urls = [];
for (var m = 0; m < 2; m++) { // why not iterate over data.results?
var cameraFeed;
// build cameraFeed ...
urls.push(cameraFeed);
}
// Update images
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
});
Of course this can still be approved, but that should point you into the right direction. Note in particular that it is unnecessary to have a setInterval for each image. Just let a single interval update all images.
Especially the for loop can be approved upon. I don't know how many results data.results has and if you only want to get the first two, but this is an excellent use case for Array#map:
var urls = data.results.map(function(result) {
// ...
return cameraFeed;
});
I am trying to get a feed from Instagram using JSON and jQuery to pull specific hashtag images from one particular user - it has been crazy so far and all built from scratch.. now I am stuck - my loop keeps saying Undefined x
This is my code
// GET INSTAGRAM FEED
// Get feed from Instagram based on Hashtag and filter by user
//
var username = 'jdsportsofficial';
var hashtag = 'crlifestyle';
var clientId = '5a79ddf3fa4147ffbea3fc0e38b22014';
var auth_token = ''; // not needed for most
var instaHTML;
var divId = '#instafeed';
jQuery.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/"+hashtag+"/media/recent?client_id="+clientId,
success: function(x) {
for (var i = 0; i < 25; i++) {
// GET THE PICTURE
// -- options are thumbnail and large - see object for more
var instaPicture = x.data[i].images.thumbnail.url;
if (x.data[i].user.username == username) {
instaHTML += "<div class='CaroselSlideItem'><img src='" + instaPicture + "'/></div>";
}
// INSERT THE GALLERY
jQuery(divId).html(instaHTML);
}
}
});
You can console it via jQuery('body').html(instaHTML);
My error is
TypeError: x.data[i] is undefined Line 707 in var instaPicture = x.data[i].images.thumbnail.url;
If x.data has less than 25 results the error could come. Assume x.data has only 20 results then when the loop reaches i=20, x.data[i] will be undefined.
So
jQuery.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/tags/" + hashtag + "/media/recent?client_id=" + clientId,
success: function (x) {
for (var i = 0; i < x.data.length && i < 25; i++) {
// GET THE PICTURE
// -- options are thumbnail and large - see object for more
var instaPicture = x.data[i].images.thumbnail.url;
if (x.data[i].user.username == username) {
instaHTML += "<div class='CaroselSlideItem'><img src='" + instaPicture + "'/></div>";
}
// INSERT THE GALLERY
jQuery(divId).html(instaHTML);
}
}
});
I have a jquery javascript to update to page every x minutes/seconds.
I want to define this update interval in a separate json-config file so that the project can be easily configurated.
I have a javascript named ConfigReader which has a method to read this config-file.
I want know to load this ConfigReader to my jQuery javascript with 'require' but because the jQuery is on Clientside it does not know require.
How can I import my ConfigReader to my jQuery javascript file?
Here is the jQuery file:
var ConfigReader = require('../libs/ConfigReader');
var update = function() {
var divs = $('div[id^="data-"]')
for (var i = 0; i < divs.length; i++) {
var id = divs[i].id;
var dataType = id.split('-')[1];
var cacheId = id.split('-')[2];
$.ajax({
type: "GET",
url: '/' + dataType + 'View?cacheId=' + cacheId,
context: id,
success: function(data) {
console.log("id=" + id + " this=" + this);
$("#" + this.replace(/\./g, '\\\.')).html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(this + "View", jqXHR, textStatus, errorThrown);
}
});
}
}
var configReader = new ConfigReader();
var configUpdate;
var configuration = configReader.getConfigutation();
for(var i = 0; i < configuration.length; i++){
var current = configuration[i];
switch(current["name"]){
case "update":
configUpdate = parseInt(current["interval"]);
break;
}
}
$(document).ready(function() {
update();
window.setInterval(update, configUpdate);
});