I have 3 files i refer to them as:
$nowplaying = file_get_contents("/api/static/nowplaying");
$dj = file_get_contents("/api/static/dj");
$listeners = file_get_contents("/api/static/listeners");
I want to call them in my php file inside div tags by using
'.$dj.'
'.$nowplaying.'
'.$listeners.'
but the contents of the files i am pulling update every 30 seconds so I need to refresh the data shown without refreshing the page. I'm thinking javascript jquery may be the one but i'm not too familiar with it.
Many thanks!
If you have jQuery
setInterval(function(){
$.get("/api/static/nowplaying",function(data){
// Do something with data
});
},30000);
with javascript kinda like
var request = new XMLHttpRequest();
setInterval(function(){
request.open('GET', '/api/static/nowplaying', true);
request.send();
},30000)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
Yes, I think using jquery/JavaScript is what you are looking for and its pretty simple. Just use the setInterval() method in JavaScript to have it repeatedly run a function on a schedule. Since you're rather new to this I'll try to make a simple example. The code below runs updateDiv() every 30 seconds.
<script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.js">
</script>
<script type='text/javascript'>
var myVar
function updateDiv(){
clearInterval(myVar);
alert('your code should go here');
myVar = setInterval("updateDiv()", 30000);
}
$(document).ready(function(){
myVar = setInterval("updateDiv()", 30000);
});
You can view this here: https://jsfiddle.net/jglazer63/h6q20dj9/1/
Related
I'm trying to switch between pages and then to manipulate the new document through javascript or jQuery.
However, when I run my example, it manipulates the first document and then changes location. Is it even possible?
this is my example(i even tried to call a function after changing location):
function openSide(x) {
//é passado o botão carregado
window.location.href = 'new.php';
var id = x.innerHTML;
open(id);
}
function open(x) {
$("#div1").css("display","none");
$("#div2").css("display","");
$("#tituloPlay").html(id);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$("#tabelaOuvirPlaylist").append(xhttp.responseText);
//console.log(xhttp.responseText);
}
};
xhttp.open("POST", "php/listarMusicasDePlaylist.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+ x);
}
Use the jQuery load() method to take data from that location and put it on your page. Then you can manipulate it from there.
Since you're opening a new PHP page, why don't you just pass the ID as a query parameter?
new.php?id=1
Adjust your PHP file to read the ID from $_GET ["id"]..
To use the ID in Javascript you would need to read the current location and do a substring the = sign or you could have PHP create a hidden DOM element and read it's value in Javascript
I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>
I am loading a page through xmlHttpRequest and I am not getting one variable which come into existance after some miliseconds when page loading is done
so the problem is when xmlHttpRequest sends back the response I do not get that variable in it.
I want it to respond back even after onload.
var xhr = new XMLHttpRequest();
xhr.open("GET", event.url, true);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() { callback(); };
xhr.followRedirects = true;
xhr.send();
I tried setTimeOut but of no use because may be at that time call is finished
xhr.onload = function() {
console.log('wait for response');
setTimeout(function(){
callback(xhr.responseText);
},2000);
};
I tried readyStateChange , but no success
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
callback(xhr.responseText);
};
};
by the way, I am trying to load amazon signIn page
and the variable which is missing everytime is hidden Input Field metadata1,
I get all other hidden Input fields in response text , except input field, named "metadat1"
I'll be more than Happy, If anyone can help.
Thanks in advance
ohh Finally I did it,
I din't read any javascript, Instead I just extracted scripts which I received in xhr calls and executed it inside a hidden div, and here it is , I got that variable's value
abc(xhr.responseText);
function abc(xhrRes){
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrdiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var scr = document.getElementById('xhrdiv').getElementsByTagName("script");
//5 scripts needed to generate the variable
for(i=0;i<5;i++){
eval(scr[i].innerHTML);
if( i+1 == 5){
var response = document.getElementById('xhrdiv').innerHTML;
return response; //and in this response variable I have every thing I needed from that page which I called through xmlhttp Req
}
}
}
---------------------Improved Version-----------------------
Instead of executing script through eval,
keep script content in a file AND Include it, as we normally include the script, that works better.
xhrRes = xhr.responseText;
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrDiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var xhrDiv = document.getElementById('xhrDiv');
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = JSfile;
xhrDiv.appendChild(newScript);
(it shows the edit is done my anonymous user, :( because I forgot to Login, while editing)
If the data doesn't exist until some time after the page has loaded then, presumably, it is being generated by JavaScript.
If you request the URL with XMLHttpRequest then you will get the source code of that page in the response. You will not get the generated DOM after it has been manipulated by JavaScript.
You need to read the JavaScript on the page you are requesting, work out how it is generating the data you want to read, and then replicate what it does with your own code.
Im currently in the learning process with AJAX & JavaScript..
I have a quick question to the wise..
How can i turn the code below into a timed event instead of an OnClick event.
**For Example i would like to refresh the "showlist" DIV every 5 seconds...
I understand that this is working code and goes against the rules of the site but if i were to post my non working code it would just confuse things as it has me..
I am trying to slowly understand the basics :)
Any guidance would be greatly appreciated
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showlist").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>
</html>
You can change loadXMLDoc function to make use of setTimeout. Consider this example:
function loadXMLDoc() {
var xmlhttp,
timer;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("showlist").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.onerror = function() {
clearTimeout(timer);
};
xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
xmlhttp.send();
timer = setTimeout(loadXMLDoc, 5000);
}
Function issues AJAX request and set up a 5s timeout. I also added basic onerror callback to clear timer just in case.
I once made a kind of tv, which automatically changed the 'screen' after 3 seconds.
Maybe you can re-use my code?
// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
if(i > (totalPics - 1)){
i = 0;
}
myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
I hope you can re-use this for your project, and I hope you kind of understand what I mean, if I need to clarify, just ask me :).
So what you need to do, is refresh the array when you got new item in your showlist.
This function (if placed inside the same script tag after your loadXMLDoc fn) will execute and call your function and then itself again every 5 seconds (recursively). You could call setInterval instead, but that runs the risk of occasionally missing a cycle if the js engine is busy:
(function doMeSelf(){
setTimeout(function(){
loadXMLDoc();
doMeSelf();
},5000);
})();
Enclosing the function def inside parens, and then followed by () is called an immediately invoked function expression.
See this question for some background: What do parentheses surrounding a object/function/class declaration mean?
Below is my javascript code snippet. Its not running as expected, please help me with this.
<script type="text/javascript">
function getCurrentLocation() {
console.log("inside location");
navigator.geolocation.getCurrentPosition(function(position) {
insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
}
function insert_coord(loc) {
var request = new XMLHttpRequest();
request.open("POST","start.php",true);
request.onreadystatechange = function() {
callback(request);
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));
return request;
}
function callback(req) {
console.log("inside callback");
if(req.readyState == 4)
if(req.status == 200) {
document.getElementById("scratch").innerHTML = "callback success";
//window.setTimeout("getCurrentLocation()",5000);
setTimeout(getCurrentLocation,5000);
}
}
getCurrentLocation(); //called on body load
</script>
What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals.
Here's the firebug screenshot:
IS there a leak in the program. please help.
EDIT: The expected outcome in the firebug console should be like this :-
inside location
POST ....
inside callback
/* 5 secs later */
inside location
POST ...
inside callback
/* keep repeating */
Probably not the problem, but I can suggest two refactorings:
Merge your two conditions in callback():
if ((req.readyState == 4) && (req.status == 200)) {
And you can shorten your setTimeout line to:
setTimeout(getCurrentLocation, 5000);
And in an effort to fix the problem, can I get you to remove the setTimeout() from callback(), and replace the call to getCurrentLocation() with it? So you're only writing "callback success" when the callback is run, nothing else.
setTimeout(getCurrentLocation, 5000); //called on body load