So I have a countdown timer that grabs a .php file when the clock hits 0. Only problem is, the php file is opening in a new window. I would like it to be displayed at the bottom of the page somehow.
I don't know anything about javascript or AJAX. Only php and html. Can anyone show a newbie what to do?
<!--START COUNTDOWN TIMER SCRIPT-->
<br>
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', 'timerunout.php', 4); } function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
document.location.href = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "When the Clock hits Zero...<br> "+timeparts[0]+":"+timeparts[1];
}
},250); // the lower this number, the more accurate the timer. 250 recommended }
</script>
<center>
<font color="#FF0000"><b><h1>
<div id="my_div1">
</div>
</h1></b></font>
</center>
<!--END COUNTDOWN TIMER SCRIPT-->
Ok so I have a countdown timer on index.php, when it hits 0... it opens another php file into the bottom of the page using AJAX. Let's call this timerunout.php
Problem is this... in that Php file is a link.
At the end of that link needs to be an affiliate ID attached to the end of it.
That affiliate ID is only detected when someone types their username at the end of the address in the index.php. Any suggestions?
Here's the code for index.php
window.onload = function() {
countDown('my_div1', 'timerunout.php', 4);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID);
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
//This code creates the AJAX object, which will then be used to send it.
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//This code parameterizes the object to point at your page in an asynchronous way.
xmlhttp.open("GET","timerunout.php?s1=username",true);
xmlhttp.send(); //Once all parameters are set, send it on it's way.
//Callback. Once the request is in one of it's stages, this will be called.
xmlhttp.onreadystatechange=function() {
//Request done and fetching the page successful?
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Sets the HTML of my_div1 to whatever was in timerunout.php
elem.innerHTML=xmlhttp.responseText;
}
}
clearInterval(timer);
} else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "When the Clock hits Zero...<br> "+timeparts[0]+":"+timeparts[1];
}
} ,250); // the lower this number, the more accurate the timer. 250 recommended } </script> <center>
<div id="my_div1"></div> </center> <!--END COUNTDOWN TIMER SCRIPT-->
and here's the timerunout.php
//
// Maybe check $s1 is indeed valid
//
$newurl = sprintf('/join.php?id=%s', urlencode($_GET['s1']));
$coaching = sprintf('/live/webinar-register.php?id=%s',
urlencode($_GET['s1']));
?>
So basically what I'm saying is that in index.php,
username in this line needs to be coming from what the user types in their address bar.
xmlhttp.open("GET","timerunout.php?s1=username",true);
If you want to use the jQuery-Framework, you might go about the matter like this:
$.ajax({
url: "timerunout.php",
data:{ s1:"whateverparametersuitsyourfancy" }
}).done(function(data) {
$('#my_div1').html(data);
});
If you want to go the traditional way, the AJAX call is a bit more complicated. From the w3schools website:
//This code creates the AJAX object, which will then be used to send it.
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//This code parameterizes the object to point at your page in an asynchronous way.
xmlhttp.open("GET","timerunout.php?s1=whateverparametersuitsyourfancy",true);
xmlhttp.send(); //Once all parameters are set, send it on it's way.
//Callback. Once the request is in one of it's stages, this will be called.
xmlhttp.onreadystatechange=function() {
//Request done and fetching the page successful?
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Sets the HTML of my_div1 to whatever was in timerunout.php
document.getElementById("my_div1").innerHTML=xmlhttp.responseText;
}
}
Both codes will send a GET request to the page in question and write the 'echoed' output of the target page to the html tag identified by 'my_div1'.
In your code (I'll use the plain JS example) this may look like this.
<!--START COUNTDOWN TIMER SCRIPT-->
<br>
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', 'timerunout.php', 4);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID);
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
//This code creates the AJAX object, which will then be used to send it.
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//This code parameterizes the object to point at your page in an asynchronous way.
xmlhttp.open("GET","timerunout.php?s1=whateverparametersuitsyourfancy",true);
xmlhttp.send(); //Once all parameters are set, send it on it's way.
//Callback. Once the request is in one of it's stages, this will be called.
xmlhttp.onreadystatechange=function() {
//Request done and fetching the page successful?
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Sets the HTML of my_div1 to whatever was in timerunout.php
elem.innerHTML=xmlhttp.responseText;
}
}
clearInterval(timer);
} else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "When the Clock hits Zero...<br> "+timeparts[0]+":"+timeparts[1];
}
} ,250); // the lower this number, the more accurate the timer. 250 recommended
}
</script>
<center>
<font color="#FF0000"><b><h1>
<div id="my_div1"></div>
</h1></b></font>
</center>
<!--END COUNTDOWN TIMER SCRIPT-->
Edit: I added a single GET parameter to the AJAX calls, to be used at your convenience.
Related
I've written a MSE video player and it's loading WebMs. These are loading well, however I have a problem with video files with no audio tracks.
I've tried changing the codec depending on if there is audio
mediaSource.addSourceBuffer(`video/webm; ${videoHasAudio(asset) ? 'codecs="vp9,vorbis"' : 'codecs="vp9"'}`)`
And I thought this was working but now isn't. How do I run silent WebMs in MSE?
I have added sample MSE project here:
https://github.com/thowfeeq178/MediaSourceExtention
checkout the example in the github
overview:
we need to add one for video and one for audio like below:
// BBB : https://dash.akamaized.net/akamai/bbb_30fps/bbb_30fps.mpd
var baseUrl = "https://dash.akamaized.net/akamai/bbb_30fps/";
var initUrl = baseUrl + "bbb_30fps_480x270_600k/bbb_30fps_480x270_600k_0.m4v";
var initAudioUrl = baseUrl + "bbb_a64k/bbb_a64k_0.m4a";
var templateUrl =
baseUrl + "bbb_30fps_480x270_600k/bbb_30fps_480x270_600k_$Number$.m4v";
var templateUrlForAudio = baseUrl + "bbb_a64k/bbb_a64k_$Number$.m4a";
var sourceBuffer;
var audioSourceBuffer;
var index = 0;
var audioIndex = 0;
var numberOfChunks = 159;
var video = document.querySelector("video");
var ms = new MediaSource();
function onPageLoad() {
console.log("page loaded ..");
if (!window.MediaSource) {
console.error("No Media Source API available");
return;
}
// making source controlled by JS using MS
video.src = window.URL.createObjectURL(ms);
ms.addEventListener("sourceopen", onMediaSourceOpen);
}
function onMediaSourceOpen() {
// create source buffer
sourceBuffer = ms.addSourceBuffer('video/mp4; codecs="avc1.4d401f"');
audioSourceBuffer = ms.addSourceBuffer('audio/mp4; codecs="mp4a.40.5"');
// when ever one segment is loaded go for next
sourceBuffer.addEventListener("updateend", nextSegment);
audioSourceBuffer.addEventListener("updateend", nextAudioSegment);
// fire init segemnts
GET(initUrl, appendToBuffer);
GET(initAudioUrl, appendToAudioBuffer);
// play
video.play();
}
// get next segment based on index and append, once everything loaded unlisten to the event
function nextSegment() {
var url = templateUrl.replace("$Number$", index);
GET(url, appendToBuffer);
index++;
if (index > numberOfChunks) {
sourceBuffer.removeEventListener("updateend", nextSegment);
}
}
// get next audio segment based on index and append, once everything loaded unlisten to the event
function nextAudioSegment() {
var audioUrl = templateUrlForAudio.replace("$Number$", audioIndex);
GET(audioUrl, appendToAudioBuffer);
audioIndex++;
if (index > numberOfChunks) {
audioSourceBuffer.removeEventListener("updateend", nextAudioSegment);
}
}
// add to existing source
function appendToBuffer(videoChunk) {
if (videoChunk) {
sourceBuffer.appendBuffer(new Uint8Array(videoChunk));
}
}
function appendToAudioBuffer(audioChunk) {
if (audioChunk) {
audioSourceBuffer.appendBuffer(new Uint8Array(audioChunk));
}
}
// just network thing
function GET(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.onload = function(e) {
if (xhr.status != 200) {
console.warn("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(xhr.response);
};
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>MSE Demo</title>
</head>
<body onload="onPageLoad()">
<h1>MSE Demo</h1>
<div>
<video muted controls width="80%"></video>
</div>
</body>
</html>
I am trying to use the Web Audio API to play sound in my React application.
It's currently playing sound in all browsers except Safari v12.1.
I am aware Safari has restrictions on autoplay and requires user interaction to play sound, so I have a play button which calls the _play() function:
_play = (url, index) => {
this._getData(url);
this.source.start(index)
}
It's calling the _getData() function which looks like this:
_getData(url) {
this.source = this.audioContext.createBufferSource();
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = () => {
var audioData = request.response;
console.log(this.audioContext)
this.audioContext.decodeAudioData(audioData, buffer => {
this.source.buffer = buffer;
this.source.connect(this.audioContext.destination);
},
function(e){ console.log("Error with decoding audio data" + e.err); });
}
request.send();
}
this.audioContext is created in the component constructor using:
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
The console.log(this.audioContext) inside the request.onload outputs this before pressing play:
...and this after pressing play:
But no sound is playing (in Safari).
What am I doing wrong?
I think the problem that you ran into is that Safari does not allow you to modify the buffer anymore once you called start().
The following page does for example play a second of noise in Safari when you press the play button.
<!DOCTYPE html>
<html>
<body>
<button id="play-button">play</button>
<script>
document
.getElementById('play-button')
.addEventListener('click', () => {
const audioContext = new AudioContext();
const audioBufferSourceNode = audioContext.createBufferSource();
const sampleRate = audioContext.sampleRate;
const audioBuffer = audioContext.createBuffer(1, sampleRate, sampleRate);
const channelData = audioBuffer.getChannelData(0);
for (let i = 0; i < sampleRate; i += 1) {
channelData[i] = (Math.random() * 2) - 1;
}
audioBufferSourceNode.buffer = audioBuffer;
audioBufferSourceNode.connect(audioContext.destination);
audioBufferSourceNode.start(audioContext.currentTime);
});
</script>
</body>
</html>
But it doesn't work anymore if you modify it slightly. When starting the audioBufferSourceNode before assigning the buffer there will be no output anymore.
audioBufferSourceNode.connect(audioContext.destination);
audioBufferSourceNode.start(audioContext.currentTime);
audioBufferSourceNode.buffer = audioBuffer;
I guess you can get your code working by waiting for the HTTP response and the audio decoding before you start the source. Make sure to execute this.source.buffer = buffer before you execute this.source.start(index).
I hope this helps.
I'm using PhantomJS to automate a page. What I do is:
do{
console.log(i);
i++;
page.open(url);
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
if(page.injectJs('./Search.js') == false){
console.log("Search.js Failed")
}
var links = page.evaluate(function(json){
return search(json)
},json)
console.log(links);
} while(links == "")
So this leads me to opening the website repeated until what I'm looking for appears. But this also leads me to getting IP banned. What can I do to get around this?
Your IP is probably getting banned because the script generates too many requests to the website in very little time. So, you need to throttle requests, to apply a pause between them.
I would rewrite your script like this:
var page = require('webpage').create();
var url = "http://www.website.tld/";
var json = {"some" : "json"};
var i = 0;
var links;
// We abstract main code to a function so that we can call it
// again and again from itself
function getlinks (url, json) {
i++;
console.log(i);
page.open(url);
do { phantom.page.sendEvent('mousemove'); } while (page.loading);
if(page.injectJs('./Search.js') == false){
console.log("Search.js Failed")
}
var links = page.evaluate(function(json){
return search(json);
}, json);
if(links == "")
{
// No links scraped yet, so we wait for 3 seconds and try again
setTimeout(function(){
getlinks(url, json);
}, 3000)
}
else
{
console.log(links);
phantom.exit();
}
}
getlinks(url, json);
I have 4 iframe and I want to recover by clicking on their id .
I walked my iframe using google analytic and I put their id in a table.
Then I create an object of type YT.Player
Probleme : the method onPlayerStateChange does not run .
here is my code :
<script type="text/javascript">
/*
YouTube Analytics
Code adapted from:
http://www.lunametrics.com/blog/2012/10/22/automatically-track-youtube-videos-events-google-analytics/
http://lunametrics.wpengine.netdna-cdn.com/js/lunametrics-youtube.js
Code adapted by Alex Mueller for ISITE Design http://isitedesign.com
*/
// enable cross-domain scripting in IE < 10 for the YouTube Data API
// https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js
if(window.XDomainRequest){jQuery.ajaxTransport(function(e){if(e.crossDomain&&e.async){if(e.timeout){e.xdrTimeout=e.timeout;delete e.timeout}var t;return{send:function(n,r){function i(e,n,i,s){t.onload=t.onerror=t.ontimeout=jQuery.noop;t=undefined;r(e,n,i,s)}t=new XDomainRequest;t.onload=function(){i(200,"OK",{text:t.responseText},"Content-Type: "+t.contentType)};t.onerror=function(){i(404,"Not Found")};t.onprogress=jQuery.noop;t.ontimeout=function(){i(0,"timeout")};t.timeout=e.xdrTimeout||Number.MAX_VALUE;t.open(e.type,e.url);t.send(e.hasContent&&e.data||null)},abort:function(){if(t){t.onerror=jQuery.noop;t.abort()}}}}})}
// load the YouTube iframe API
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// initialize our arrays to hold video and player information
var playerArray = [],
videoArray = [];
// safely pass the jQuery object as $
(function($) {
// enables tracking of all YouTube videos on the page
function trackYouTube() {
// iterate through every iframe on the page
$('iframe').each(function(i) {
// grab the video source and other properties
var baseUrlLength,
$iframe = $(this),
iframeSrc = $iframe.attr('src'),
isYouTubeVideo = false,
videoID,
url;
// if the video uses the http protocol
if (iframeSrc.substr(0,25) == "http://www.youtube.com/v/") {
baseUrlLength = 25;
isYouTubeVideo = true;
}
// otherwise if the video uses the https protocol
else if (iframeSrc.substr(0,26) == "https://www.youtube.com/v/") {
baseUrlLength = 26;
isYouTubeVideo = true;
}
// if we're dealing with a YouTube video, store its information in our arrays
if (isYouTubeVideo) {
// grab the videoID
videoID = iframeSrc.substr(baseUrlLength);
url = '//gdata.youtube.com/feeds/api/videos/' + videoID + '?v=2&alt=json';
// if the ID ends with extra characters...
if (videoID.indexOf('&') > -1) {
// ...remove the extra characters
videoID = videoID.substr(0, videoID.indexOf('&'));
}
// put an object in our array with the videoID...
videoArray[i] = {};
videoArray[i].id = videoID;
// put the videoID on the iframe as its id
$iframe.attr('id', videoID);
}
});
}
$(function() {
// initiate tracking on document ready
trackYouTube();
onYouTubeIframeAPIReady();
});
})(jQuery);
function onYouTubeIframeAPIReady() {
// insert YouTube Player objects into our playerArray
for (var i = 0; i < videoArray.length; i++) {
playerArray[i] = new YT.Player(videoArray[i].id, {
events: {
'onStateChange': onPlayerStateChange
}
});
}
}
// when the player changes states
function onPlayerStateChange(event) {
// if the video begins playing, send the event
if (event.data == YT.PlayerState.PLAYING) {
alert();
}
// if the video ends, send the event
if (event.data == YT.PlayerState.ENDED) {
alert();
}
}
</script>
You have to set the enablejsapi parameter to 1 in your iframe embed link.
By default, the parameter is set to 0 and unless you set it to 1, the callbacks won't work.
Reference: https://developers.google.com/youtube/js_api_reference
How can I add Page transitions effects like IE in Safari for web pages?
You could check out this example: http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted:
var xmlhttp;
var timerId = 0;
var op = 1;
function getPageFx() {
url = "/transpage2.html";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange=xmlhttpChange
xmlhttp.open("GET",url,true)
xmlhttp.send(null)
} else getPageIE();
}
function xmlhttpChange() {
// if xmlhttp shows "loaded"
if (xmlhttp.readyState == 4) {
// if "OK"
if (xmlhttp.status == 200) {
if (timerId != 0)
window.clearTimeout(timerId);
timerId = window.setTimeout("trans();",100);
} else {
alert(xmlhttp.status)
}
}
}
function trans() {
op -= .1;
document.body.style.opacity = op;
if(op < .4) {
window.clearTimeout(timerId);
timerId = 0; document.body.style.opacity = 1;
document.open();
document.write(xmlhttp.responseText);
document.close();
return;
}
timerId = window.setTimeout("trans();",100);
}
function getPageIE() {
window.location.href = "transpage2.html";
}
Check out Scriptaculous. Avoid IE-Only JS if that's what you are referring to (no idea what kind of effect you mean).