HTA File Caching causing major issues - javascript

I have a JavaScript function which first of all fetches the value of a label element, which is an ID for a database entry. These ID's then get sent to a ASP page which fetch an images save location from the database.
This save location information for each selected image is then sent to a ASP.NET page which splits each image save location and rotates the images accordingly. This all works perfect, my only issue is that the images will not update until I reopen the HTA file.
Refreshing does not work, as seen in the video.
The files HAVE rotated as you can see in the video at the bottom
Here is the link to the video!
Here is my JavaScript which does the rotating:
function doRotate(dir,obj)
{
var http = getHTTPObject();
var http2 = getHTTPObject();
ids = fetchSelection().toString();
//Make button animate, visual aid that it is working
obj.src = "http://localhost/nightclub_photography/images/buttons/"+dir+"_animated.gif";
http.onreadystatechange = function()
{
//Fetch the save location of selected images
if (http.readyState == 4 && http.status == 200) {
//Create URL string to send to rotate script
var locs = http.responseText;
locs = locs.split(",");
//Start of URL
var url = "http://localhost/nightclub_photography/net/rotate_script.aspx?dir=" + dir;
for (var i=0; i < locs.length-1; i++)
{
url = url + "&t=" + locs[i];
}
//Add random math
url = url + "&k=" + Math.random();
http2.onreadystatechange = function()
{
if (http2.readyState == 4 && http2.status == 200)
{
//Stop animated button
obj.src = "http://localhost/nightclub_photography/images/buttons/"+dir+".png";
//Split id's
var idsSplit = ids.split(",");
for (var k=0; k < idsSplit.length; k++) {
reapplyStyle(idsSplit[k]);
}
}
}
http2.open("GET", url);
http2.send();
}
}
http.open("GET", "http://localhost/nightclub_photography/asp/returnDatabaseData.asp?ids="+ids+"&k=" + Math.random());
http.send();
}
I also have a function which reapplies (well, should do) the background image, which should reload the rotated images. Although reloading the page doesn't work, so I can't see that function working either, but that's a different issue. Here is the function:
function reapplyStyle(id) {
var background = doc(id+"_label").style.backgroundImage;
doc(id+"_label").style.backgroundImage = background;
}

If it is a caching problem, have you tried making the image url unique. Try something like this:
ts = new Date().getTime();
obj.src = "http://localhost/nightclub_photography/images/buttons/"+dir+".png?timestamp=" + ts;

Related

Converting Jquery to Vanilla JS stuck on AJAX

I am trying to convert an older jquery script to vanilla JS.
I have been working through most of them just one by one but am having a problem with the ajax call. Can anyone look at my original file and new file and see what is missing?
I am struggling mostly with converting the initial function calls to vanilla js. If you look at the 2nd code drop there most of the 'jquery-isms' have been rewritten in vanilla js. However I am having trouble converting my $.merge and $.extend actions. Furthermore, converting the $.ajax call to a JS version.
I tried to work on it modularly task by task but still haven't gotten it completely polished.
Jquery
(function($){
$(document).ready(function() {
$.ajax({
url: "https://api.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=*PRIVATE*c&gallery_id=72157720949295872&per_page=10&format=json&nojsoncallback=1",
type: "GET",
success: function(data) {
console.log("api successfully called")
let path = data.photos.photo
//for each photo, I save the different individual ids into variables so that they can be easily plugged into a URL
for (let i = 0; i < path.length; i++) {
let obj = path[i];
let farm_id = data.photos.photo[i].farm
let server_id = data.photos.photo[i].server
let photo_id = data.photos.photo[i].id
let secret = data.photos.photo[i].secret
//the static address to photos on Flickr is accessed through this address: https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
//this variable is the direct link to access photos on Flickr, minus the ".jpg" designation that will be added, according to whether we are trying to access the medium picture or the large picture
let pic_url = "https://farm" + farm_id + ".staticflickr.com/" + server_id + "/" + photo_id + "_" + secret;
//this is the variable that stores the medium jpeg URL
let pic_url_m = pic_url + "_m.jpg";
//this stores an image tag which will be populated with a medium jpeg URL
let pic_img = ('<img src=\'' + pic_url_m + '\' alt = \"pic\" />');
//this appends the var pic_img to the photo_list div as the function loops through
//$('.body').append('#frame');
$('#photo-list').append(pic_img);
//this appends the class "paginate" to each img tag that is formed, ensuring that the the divs get passed to a later function called customPaginate
// $('img').addClass("paginate")
$('#photo-list img').addClass("paginate");
}
//this passes all divs with the class "pagination" to the function customPaginate
$('.pagination').customPaginate({
itemsToPaginate: ".paginate"
});
//when img tags with the class paginate are clicked, the following function is called
$('.paginate').click(function() {
//this variable saves the "src" or URL of (this) which is any element with the class "paginate"
let src = $(this).attr('src');
//this variable takes the "src" variable, slices the last six characters, and replaces it with "_c.jpg", a large version of the image URL
let src_l = src.slice(0, -6) + "_c.jpg";
//gives the "frame img" element a new attribute, which is the large image URL
$('#frame img').attr('src', src_l);
//allows the the "frame img" element to fade into the screen
$('#frame img').fadeIn();
//allows the "overlay" element to fade onto the screen
$('#overlay').fadeIn();
//when the "overlay" element is clicked, both the "overlay" and "frame img" elements
$('#overlay').click(function() {
$(this).fadeOut();
$('#frame img').fadeOut();
//removes the "src" attribute from "frame img", allowing it to be populated by other image URLs next time an image is clicked
$('#frame img').removeAttr('src');
});
});
}
});
});
//this function generates the customPaginate function, which paginates the images 10 to a page
$.fn.customPaginate = function(options)
{
let paginationContainer = this;
let defaults = {
//sets how many items to a page
itemsPerPage : 10
};
let settings = {};
//merges defaults and options into one one variable, settings
$.extend(settings, defaults, options);
//sets how many items will be on each page
let itemsPerPage = settings.itemsPerPage;
//sets which items are going to be
let itemsToPaginate = $(settings.itemsToPaginate);
//determines how many pages to generate based on the amount of items
let numberOfItems = Math.ceil((itemsToPaginate.length / itemsPerPage));
//this ul will contain the page numbers
$("<ul></ul>").prependTo(paginationContainer);
//loops through the ul tag the same number of times as there are pages. in this case, the loop will run 4 times
for(let index = 0; index < numberOfItems; index++)
{
paginationContainer.find('ul').append('<li>'+ (index+1) + '</li>');
}
//ensures that the current page only displays the items that should be on the specific page, and hides the others
itemsToPaginate.filter(":gt(" + (itemsPerPage - 1) + ")").hide();
//locates the first li element, adds activeClass element to it
paginationContainer.find("ul li").first().addClass(settings.activeClass).end().on('click', function(){
let $this = $(this);
//gives current page the activeClass setting
$this.addClass(settings.activeClass);
//takes activeClass setting away from non-current pages
$this.siblings().removeClass(settings.activeClass);
let pageNumber = $this.text();
//this variable designates that items located on the previous page times the number of items per page should be hidden
let itemsToHide = itemsToPaginate.filter(":lt(" + ((pageNumber-1) * itemsPerPage) + ")");
//this function merges itemsToHide and itemsToPaginate that are greater than the product of the pageNumber and the itemsPerPage minus 1, ensuring that these items are hidden from view
$.merge(itemsToHide, itemsToPaginate.filter(":gt(" + ((pageNumber * itemsPerPage) - 1) + ")"));
//designates these items as items that should be shown on the current page
let itemsToShow = itemsToPaginate.not(itemsToHide);
//hides items from other pages and shows items from current page
$("html,body").animate({scrollTop:"0px"}, function(){
itemsToHide.hide();
itemsToShow.show();
});
});
}
}(jQuery));
Vanilla JS (what im still stuck on)
(function($){
document.querySelector(document).ready(function() {
$.ajax({ //need to convert this to JS
url: "https://api.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=*PRIVATE*c&gallery_id=72157720949295872&per_page=10&format=json&nojsoncallback=1",
type: "GET",
success: function(data) {
console.log("api successfully called")
// ....truncated
}
});
});
$.fn.customPaginate = function()
{
let paginationContainer = this;
let defaults = {
itemsPerPage : 10
};
let settings = {};
//need to convert this extend to JS
$.extend(settings, defaults, options);
let itemsPerPage = settings.itemsPerPage;
// ....truncated
let pageNumber = qS.text();
let itemsToHide = itemsToPaginate.filter(":lt(" + ((pageNumber-1) * itemsPerPage) + ")");
//need to convert this extend to JS
$.merge(itemsToHide, itemsToPaginate.filter(":gt(" + ((pageNumber * itemsPerPage) - 1) + ")"));
});
}
}(jQuery));
First, please see: https://www.w3schools.com/js/js_ajax_intro.asp
Example you might consider.
function getPages(){
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
// Everything you want to do with the data
// this.responseText.photos.photo
}
xmlhttp.open("GET", "https://api.flickr.com/services/rest/?method=flickr.galleries.getPhotos&api_key=*PRIVATE*c&gallery_id=72157720949295872&per_page=10&format=json&nojsoncallback=1",);
xmlhttp.send();
}

Download three 1st images from a URL in background

I'm actually trying to find a way in a js script to downloading the three first images from a specifiq URL.
I have find this way to download img file as a new filename, but this script don't limit the imgs downloads to three:
download-data-url-file.
Why only the three images from an URL ?
Because i would like to setup later a sort of timer to repeat the downloading task.
The URL is a content feed (http://feed.500px.com/500px-best)
Basically, the img source URL is avalaible if we enter in the Inspector tool on Firefox, we can see the URL source for a give image like:
<img xmlns="http://www.w3.org/1999/xhtml" src="https://drscdn.500px.org/photo/266885357/m%3D900/v2?webp=true&sig=b5a6df5651c4248defdeee0f5b4d1ec599d87d5fa69e7673b5d64cef5a4deeb7" />
So the js script will take the first image from the website, and download the .png image as a newfilename.png (just an filename exemple), reapeat the step for a second and a third image, and stop to run.
There is an short js that i have modded for my task, i assume that i can improve it by adding an var totalImages = 3 to limiting the total img downloads..
var data = canvas.toDataURL("http://feed.500px.com/500px-best/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "Image1.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
Thank in advance.
// This code is very specific to 500PX
// I had to use itemcontent selector, as the feed was giving small icons
// as first three images.
var parents = document.getElementsByClassName("itemcontent");
var totalImages = 3;
var done = false;
var result = [];
for(var i = 0; i < parents.length && !done; i++) {
var images = parents[0].getElementsByTagName("img");
for(var j = 0; j < images.length && !done; j++) {
result.push(images[j].src);
if(result.length == totalImages)
done = true;
}
}
// The result array contains the first three images of the page.

How to display image from another page in my page

I want to start a greasemonkey plugin to an existing page. The plugin should fetch and display some images automatically, each image from different pages.
I thought of using jQuery.get("link", function(data)) and hide the page and display the images only but on an average to display 4 images I should load 6 webpages into present webpage it is creating a delay in loading.
Is there any other work around to create a function that loads the page html of all image pages in background or in another tab and get the href of <a> tag's in that page, into my page and load only images into my page?
You can try this solution below.
Just put the URLs you want in the "pages" array. When the script runs, it makes Ajax calls in the background. When they are ready, it searches the source returned for images and picks one randomly. If found, it wraps the image in a link to the page where it found it (or if available, the image's url) and inserts the linked image to the top of the body of your own current page.
You can try the code by pasting it into your browser's JavaScript console and it will add the images to the current page.
You also see a demo here: http://jsfiddle.net/3Lcj3918/3/
//pages you want
var pages =
[
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random'
]
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//when source returned, run callback with the response text
successCallback(xhr.responseText);
}
};
//requires a proxy url for CORS
var proxyURL = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyURL+url, true);
//set headers required by proxy
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.setRequestHeader("Access-Control-Allow-Origin","https://cors-anywhere.herokuapp.com/");
xhr.send();
}
//a function that extract images from given url and inserts into current page
function injectImagesFrom(url)
{
getSubPageSource(url, function(data)
{
//trim source code to body only
var bodySource = data.substr(data.indexOf('<body ')); //find body tag
bodySource = bodySource.substr(bodySource.indexOf('>') + 1); //finish removing body open tag
bodySource = bodySource.substring(0, bodySource.indexOf('</body')); //remove body close tag
//create an element to insert external source
var workingNode = document.createElement("span");
//insert source
workingNode.innerHTML = bodySource;
//find all images
var allImages = workingNode.getElementsByTagName('img');
//any images?
if (allImages.length > 0)
{
//grab random image
var randomIndex = Math.floor(Math.random() * allImages.length);
var randomImage = allImages.item(randomIndex);
//add border
randomImage.setAttribute('style', 'border: 1px solid red;');
//restrain size
randomImage.setAttribute('width', 200);
randomImage.setAttribute('height', 200);
//check if parent node is a link
var parentNode = randomImage.parentNode;
if (parentNode.tagName == 'A')
{
//yes, use it
var imageURL = parentNode.getAttribute('href');
}
else
{
//no, use image's page's url
var imageURL = url;
}
//add a link pointing to where image was taken from
var aLink = document.createElement("a");
aLink.setAttribute('href', imageURL);
aLink.setAttribute('target', '_blank');
//insert image into link
aLink.appendChild(randomImage);
/* INSERT INTO PAGE */
//insert image in beginning of body
document.body.insertBefore(aLink,document.body.childNodes[0]);
//remove working node children
while (workingNode.firstChild) {
workingNode.removeChild(workingNode.firstChild);
}
//unreference
workingNode = null;
}
});
}
for (var ii = 0, nn = pages.length; ii < nn; ii++)
{
injectImagesFrom(pages[ii]);
}

How to gather info from users with <textarea> JavaScript and save it? (website users uploading info)

I'm trying to add a option for users to upload a youtubelink which will show on the page. The script should gain the .value of the textarea and send this to a var array of YouTube links.
Code:
var array=["npvNPORFXpc", "CcsUYu0PVxY", "dE_XVl7fwBQ", "iIwxR6kjTfA", "USe6s2kfuWk"];
var iframe = document.getElementById('frame');
var previousRandom = "npvNPORFXpc"; // initial video
document.getElementById('random').addEventListener('click', function () {
do {
var random = array[Math.floor(Math.random() * array.length)];
} while (previousRandom === random)
var url="http://www.youtube.com/embed/"+random;
previousRandom = random;
iframe.src = url;});
document.getElementById('prevVideo').addEventListener('click', function () {
var curIndex = array.indexOf(previousRandom);
curIndex--;
if (curIndex < 0)
{
curIndex = array.length -1;
}
var video = array[curIndex];
var url="http://www.youtube.com/embed/"+video;
previousRandom = video;
iframe.src = url;
});
So I want users of my site to be able to add YouTube URL which the script should add to the var array. I don't know much of JavaScript but I've been trying all night and just can't find it out.
Check it out : http://jsfiddle.net/KgJ9J/1/
If you want to store the data on the server, you will need a server side script. HTML as well as Javascript are processed on the client side. PHP might do it for you

Im designing a chess game in HTML,i want to change one charecter from on position to another

i have designed chess board using buttons.Initially all the values on the button will be null,upon loading the page all the pieces appear on them and the piece of code is as follows
<input type="button" id="A8" value="" style="background:#FFE4C4;font-size: 70px;height:90;width:100" onclick="check(this.id)">
and in the onLoad function,the ASCII charecter of the chess pieces are assigned as follows:
document.getElementById('A1').value=String.fromCharCode(9814);
Now what i want is to change the one piece from a button to another on clicking two buttons.i had tried a lot with the following script
function check(clicked_id) {
var Button_2 = "";
if (i < 2) {
i++;
// alert("i:"+i);
if (i == 1) {
Button_1 = clicked_id;
B1_val = document.getElementById(Button_1).value;
alert("B1 Button val:" + B1_val);
}
if (i == 2) {
var Button_2 = clicked_id;
B2_val = document.getElementById(Button_2).value;
alert("b1 val:" + B1_val);
alert("B2 val:" + B2_val);
B2_val = B1_val;
B1_val = "";
alert("B1 val:" + B1_val + "B2 val:" + B2_val);
}
} else {
alert("Only 2 butons should press..i:" + i);
i = 0;
}
// alert("clcked a button:"+clicked_id);
}
But the code is not working
If you just want to move the value from the location of the first click to the location of the second click, then you can do that fairly simply like this:
var lastClick;
function check(id) {
var src, dest;
if (!lastClick) {
// no previous click so just store the location of this first click
lastClick = id;
} else {
// move value from lastClick id to new id
src = document.getElementById(lastClick);
dest = document.getElementById(id);
dest.value = src.value;
src.value = "";
lastClick = null;
}
}
I assume that a real application would need all sorts of error handling that doesn't let you put a piece on top of another piece, ignores first clicks on empty spaces, enforces only legal moves, etc...

Categories

Resources