Below is the snippet of my code that I am using. Actually video that I am loading is of about 1GB, so incase user has medium internet connection, the ajax times out the request, before the video gets fully loaded.
Hence I want to reset ajax time out period to 1 day, so that it doesn't gets timed out.
$(window).load(function(){
console.log("Downloading video...hellip;Please wait...");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'video/video.m4v', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
console.log("got it");
var myBlob = this.response;
var vid = (window.webkitURL ? webkitURL : URL).createObjectURL(myBlob);
// myBlob is now the blob that the objec8t URL pointed to.
var video = document.getElementById("video");
console.log("Loading video into element");
video.src = vid;
// not needed if autoplay is set for the video element
// video.play()
//alert(1);
windowLoad();
$('body').removeClass('loading');
}
}
xhr.send();
});
Thanks
You can set the XMLHttpRequest.timeout
xhr.timeout = 86400000; // 1 day in milliseconds
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
Related
It is my AJAX call with setTimeout
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById('mainContent').style.display = 'none';
if (this.readyState == 4 && this.status == 200) {
xhttp.onload = function(){
document.getElementById("mainContent").innerHTML = this.responseText;
setTimeout(function(
document.getElementById("mainContent").style.display = 'block';
),1000);
}
}
};
xhttp.open("POST", "system.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lang="+lang);
I want detect when ajax is fully loaded and I have also solution here
I have solution here but I can't understand how it work.
var oldOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
// fires on every readystatechange ever
// use `this` to determine which XHR object fired the change event
}
XMLHttpRequest.prototype.open = function() {
// when an XHR object is opened, add a listener for its readystatechange events
this.addEventListener("readystatechange", onStateChange)
// run the real `open`
oldOpen.apply(this, arguments);
}
Can you example me how it work or write full code how it work ?
I have this radio and I'm currently working on getting it to Play, Stop, Play Last, and Play Next. While trying to figure out the Play Last and Play when you get an error on the first load, I ended up running into an issue where it tries to run through my loop again before being called to and fails to load the content as it already has content. After 3-4 tries it stops looping as it should have.
Currently it plays the same song over and over if I click next instead of playing the next song it plays the same thing. Otherwise it does nothing automatically. I believe the issue is with a code; somewhere being wrong.
In the code I tried to set a var code; to route the actions through the program.
My idea of how the code should work:
code = 1; This should loop though songs after song endlessly playing.
code = 0; This should play the last played song unless the current is the first song. Then become code 1.
code = 2; It looked to me like there was an endless loop so I used 2 as a stop point for loops.
This is all of the parts that has something to do with the current song.
It's probably easier to understand the code if you read the controls first. It ALWAYS starts with playNext();
Part one gets the link to the file
//Part One - Get file directory
function partOne(){
$.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(returnData) {
data = returnData;
lastData = data;
console.log(data);
console.log('Step1')
playFirst();
}
});
};
partOne();
This part routes the code to the correct location.
//Step 2 - Code Highway - Gets new song or sends loop to trash and plays last/current song.
function codeRoute(){
document.getElementById("playSampleButton").disabled = true;
setTimeout(function(){document.getElementById("playSampleButton").disabled = false;},5000);
if (code === 1){
$.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(returnData) {
data = returnData;
console.log(data);
code=2;
sourceNode.stop(0);
playFirst();
}
});
}if(code === 0);{
code = 2;
sourceNode.stop(0);
console.log(code)
console.log('0step2')
playFunct();
}
console.log('Step2')
};
Probably useless but this part loads and plays the selected file.
//Step 3 Loads and plays song
//Load and Play current/next song
function playFirst(){
document.getElementById("songName").innerHTML = data;
fileChosen = true;
setupAudioNodes();
var request = new XMLHttpRequest();
console.log('Step3')
request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);
request.open('GET', data, true);
request.responseType = 'arraybuffer';
// When loaded decode the data
request.onload = function() {
code=1;
$("#title").html("Infinite");
$("#album").html("Infinite");
$("#artist").html("Valence");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");
// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
};
//Load and Play last/Current when autoplay blocked.
function playFunct(){
document.getElementById("songName").innerHTML = lastData;
fileChosen = true;
setupAudioNodes();
console.log('Step3.5')
var request = new XMLHttpRequest();
request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);
request.open('GET', lastData, true);
request.responseType = 'arraybuffer';
// When loaded decode the lastData
request.onload = function() {
$("#title").html("Infinite");
$("#album").html("Infinite");
$("#artist").html("Valence");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");
// decode the lastData
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
console.log(lastData)
console.log(code)
console.log('0step3')
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
};
//Step 4
//Auto plays next song. Trashes loop.
var audioBuffer;
var sourceNode;
function setupAudioNodes() {
// setup a analyser
analyser = context.createAnalyser();
// create a buffer source node
sourceNode = context.createBufferSource();
//connect source to analyser as link
sourceNode.connect(analyser);
// and connect source to destination
sourceNode.connect(context.destination);
//start updating
rafID = window.requestAnimationFrame(updateVisualization);
sourceNode.onended = function() {
console.log('Step4')
if(code === 1){
codeRoute();
}if(code === 2){
console.log('Trash Deleted')
}
}
};
Update: The full above code fully working if anyone is interested:
//Part One - Get file directory
function partOne(){
$.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(returnData) {
data = returnData;
lastData = data;
console.log(data);
console.log('Step1')
playFirst();
}
});
};
partOne();
//Step 2 - Code Highway - Gets new song or sends loop to trash and plays last/current song.
function codeRoute(){
document.getElementById("playSampleButton").disabled = true;
setTimeout(function(){document.getElementById("playSampleButton").disabled = false;},5000);
if (code === 1){
$.ajax({
url: '../scripts/radio.php',
data: {
attr1: 'value1'
},
success: function(returnData) {
data = returnData;
console.log(data);
code=2;
sourceNode.stop(0);
playFirst();
}
});
}if(code === 0){
code = 2;
sourceNode.stop(0);
console.log(code)
console.log('0step2')
playFunct();
}
console.log('Step2')
};
//Step 3 Loads and plays song
//Load and Play current/next song
function playFirst(){
document.getElementById("songName").innerHTML = data;
fileChosen = true;
setupAudioNodes();
var request = new XMLHttpRequest();
console.log('Step3')
request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);
request.open('GET', data, true);
request.responseType = 'arraybuffer';
// When loaded decode the data
request.onload = function() {
code=1;
$("#title").html("Infinite");
$("#album").html("Infinite");
$("#artist").html("Valence");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");
// decode the data
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
};
//Load and Play last/Current when autoplay blocked.
function playFunct(){
document.getElementById("songName").innerHTML = lastData;
fileChosen = true;
setupAudioNodes();
console.log('Step3.5')
var request = new XMLHttpRequest();
request.addEventListener("progress", updateProgress);
request.addEventListener("load", transferComplete);
request.addEventListener("error", transferFailed);
request.addEventListener("abort", transferCanceled);
request.open('GET', lastData, true);
request.responseType = 'arraybuffer';
// When loaded decode the lastData
request.onload = function() {
code=1;
$("#title").html("Infinite");
$("#album").html("Infinite");
$("#artist").html("Valence");
onWindowResize();
$("#title, #artist, #album").css("visibility", "visible");
// decode the lastData
context.decodeAudioData(request.response, function(buffer) {
// when the audio is decoded play the sound
sourceNode.buffer = buffer;
sourceNode.start(0);
console.log(lastData)
console.log(code)
console.log('0step3')
$("#freq, body").addClass("animateHue");
//on error
}, function(e) {
console.log(e);
});
};
request.send();
};
//Controls
//Play A Song Again
function playAgain(){
console.log(data);
code = 0;
codeRoute();
}
//Stop Playing
function stopPlaying(){
code = 2;
sourceNode.stop(0);
}
//Play Next Song
//Step 1
function playNext(){
if(context.state == 'suspended'){
code =0;
playFunct();
}else{
code =1;//0; to play last song.
console.log(code)
codeRoute();
}
}
//Step 4
//Auto plays next song. Trashes loop.
var audioBuffer;
var sourceNode;
function setupAudioNodes() {
// setup a analyser
analyser = context.createAnalyser();
// create a buffer source node
sourceNode = context.createBufferSource();
//connect source to analyser as link
sourceNode.connect(analyser);
// and connect source to destination
sourceNode.connect(context.destination);
//start updating
rafID = window.requestAnimationFrame(updateVisualization);
sourceNode.onended = function() {
console.log('Step4')
if(code === 2){
console.log('Trash Deleted')
}else{
if(code === 1){
codeRoute();
}
}
}
};
In the section labeled "This part routes to the current location" the snippet:
if(code === 0);{
code = 2;
sourceNode.stop(0);
console.log(code)
console.log('0step2')
playFunct();
}
The if statement should not have a semi-colon (i.e.)
if(code === 0){
code = 2;
sourceNode.stop(0);
console.log(code)
console.log('0step2')
playFunct();
}
I'm trying to get all the images in a folder with an AJAX request (for use in an image slider). I've found this jQuery solution which works perfectly fine, except that it uses jQuery. What would a pure JS equivalent look like? (i.e. XMLHttpRequest)
Thanks to #FZs help this is what I ended up with. Thank you!
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
You can do it without jQuery! Maybe with more code, but this should work (adapted from this post)):
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
var elements=(new DOMParser()).parseFromString(ajax.responseText,"text/html").getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()
Or, you can force XMLHttpRequest to parse document (idea from #Rainman's comment):
ajax.responseType = "document"
So the code becomes to the following:
var folder = "images/";
var ajax=new XMLHttpRequest()
ajax.open("GET",folder,true)
ajax.onload=function () {
ajax.responseType="document"
var elements=ajax.responseText.getElementsByTagname("A")
for(x of elements){
if(request.status[0]==2 && x.href.match(/\.(jpe?g|png|gif)$/)) {
let img=document.createElement("IMG")
img.src=folder+x.href
document.body.appendChild(img);
}
};
}
ajax.send()
So I have a webpage with two image elements. It is basically a website where you upload an image and it encrypts a secret massage with steganography. I want to show the difference that is not otherwise visible and I found Resemble.js which is a library to compare images. It gets two files as arguments and I would like to use my image sources instead of files since I don't want to save the images generated.
To sum up, I want to get rid of the requests and get my images via sources in the HTML but I don't know how to get it to work with Resemble.js since it accepts only files.
How the second image is generated:
cover.src = steg.encode(textarea.value, img, {
"width": img.width,
"height": img.height
});
The JavaScript working with files:
(function () {
var xhr = new XMLHttpRequest();
var xhr2 = new XMLHttpRequest();
var done = $.Deferred();
var dtwo = $.Deferred();
try {
xhr.open('GET', 'static/original.png', true);
xhr.responseType = 'blob';
xhr.onload = function (e) { done.resolve(this.response); };
xhr.send();
xhr2.open('GET', 'static/encoded.png', true);
xhr2.responseType = 'blob';
xhr2.onload = function (e) { dtwo.resolve(this.response); };
xhr2.send();
} catch (err) {
alert(err);
}
$('#example-images').click(function () {
$.when(done, dtwo).done(function (file, file1) {
if (typeof FileReader === 'undefined') {
resembleControl = resemble('./static/original.png')
.compareTo('./static/encoded.png')
.onComplete(onComplete);
} else {
resembleControl = resemble(file)
.compareTo(file1)
.onComplete(onComplete);
}
});
return false;
});
}());
I am uploading a file via ajax request, by simply splitting them in to chunks.
The problem is progress event, Firefox for some reason doesn't want to fire that event, here is my code (most of the unnecessary code is removed)
//slice file
if(file.mozSlice){
chunk = file.mozSlice(startByte, endByte);
}else if(file.slice){
chunk = file.slice(startByte, endByte);
}else{
chunk = file;
isLast = true;
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e){
console.log('progress');
}, false);
xhr.upload.addEventListener('error', function(e){
console.log("upload error!");
});
xhr.onreadystatechange = function(e){
if(this.readyState == 4 && this.status == 200){
//this chunk has bee uploaded, proceed with the next one...
}
}
xhr.open('POST', "", true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//header
xhr.setRequestHeader('Content-Type', 'application/octet-stream');//generic stream header
xhr.send(chunk);
I'm sure i haven't made any big mistakes since chrome works without any problems, so there must be some Firefox related issue.
for Chrome:
xhr.upload.addEventListener('progress', function(e) {
console.log('progress');
}, false);
for Firefox:
xhr.addEventListener('progress', function(e) {
console.log('progress');
}, false);
I checked my implementation I'm adding the progress event after I call xhr.open, maybe that fixes it?
Try the 2nd code sample here: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress does that work?