I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable.
Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.
<?php
set_time_limit(0);
while(true)
{
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
echo $jsonContent;
sleep(10);
}
?>
And here my javascript code.
setInterval(function(){
var jsonUpdPostData = <?php echo $jsonContent; ?>;
}, 100);
What should i do to make it work? Any suggestion will be appreciated.
You can make it work this way:
getContent.php
<?php
echo file_get_contents('http://megarkarsa.com/gpsjson.php');
xxxx.js
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText); // this contains the new file contents
}
}
xmlhttp.open('GET', 'getContent.php');
xmlhttp.send();
}, 100);
Related
Thanks to my previous posts, some of yall helped me setting this piece of code right there. :). It lists files in the current folder.
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"></th></tr>";
}
?>
I now want to add an "info" button at the end of every file name. I succeeded. :)
Only thing is, its only able to display static text- I want that info tab to display information about the selected file. I then did some research on AJAX.
I came up with this code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", ".info.php", true);
xhttp.send();
This code successfully loads dynamically a page called ".info.php".
Heres the tricky part: How can I make AJAX transfer a variable (the file name) to .info.php - so that info.php can display information about the selected file?
=======EDIT: Came up with this AJAX code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=<?php echo "{$filename}" ?>", true);
xhttp.send();
}
Im now able to pass variables! (Thanks Jeff)
Sadly, the passed variable is always setted as the last file in the list, instead of being setted by the selected file. Any tips?
=========EDIT #2===========
My code right now:
First is PHP
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"> </th></tr>";
}
?>
Now for the AJAX:
function loadDoc(filename) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);
xhttp.send();
}
Cheers.
You need to pass the specific filename as a parameter to your PHP page.
The issue with your first update is that foreach iterates over the array assigning the value to the "temporary" variable.
foreach (glob("*") as $filename) {
After the iteration is complete that variable ($filename, which should be considered temporary) contains only the last value of that array. So your JS function just has a statically defined file name.
The JS call should pass in the filename, and the JS function should take in a value and use it when making the call.
PHP:
onclick=\"loadDoc('{$filename}')\"
JS:
function loadDoc(filename) {
....
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);
Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
I have made a simple chat script using jquery and AJAX but the huge hole in it is that i can only chat with myself properly :P
heres the javascript for my main file
<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#status").load('ajaxLoad.php');
$("#userArea").submit(function(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var name = '<?php echo $name; ?>';
var url = "ajaxPost.php";
var msg = document.getElementById("messages").value;
var vars = "messages="+msg+"&id="+id+"&name="+name;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
$("#status").append(return_data);
}
}
hr.send(vars);
return false;});
});
and heres my 2nd file "ajaxLoad.php"
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT messages,id FROM chat");
while($row = mysql_fetch_array($sql))
{
echo $row["messages"];
}
?>
Now what i need is to continually refresh "ajaxLoad.php" so that users can chat in realtime without refreshing the page...any way around this?
// reload every second
setInterval(function() {
$("#status").load('ajaxLoad.php');
}, 1000);
Be careful of making too requests to the server. It's going to be rather intensive.
You can use javascript setInterval to call your php script every x seconds.
https://developer.mozilla.org/en/window.setInterval
If you want to get bleeding edge, you should look into WebSockets.
I'm trying to get some data from a PHP file which only gives a number after executing:
<?php
include '../assets/class/login/loginsys.php';
$extension = new extension;
$count = $extension->userCount();
echo $count;
?>
So the $count variable will be just a number. And I'm trying to retrieve that number and put it in a js variable for further use ( I need it a few times, if it were only once I would have used $.get() and applied it to the container I need ):
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onreadystatechange = function (oEvent) {
if (oXHR.readyState === 4) {
if (oXHR.status === 200) {
console.log(oXHR.responseText)
} else {
console.log("Error", oXHR.statusText);
}
}
};
oXHR.send();
I have tried the method above with little success, but I also tried it like this:
var users = $.get('admin/user-count.php', function(data) {
console.log('There are '+data+' users found');
return data;
});
The same result, nothing. So what am I doing wrong or how should I do it right ?
EDIT I have made a little mistake that I fixed now, the first method works as well as the second one. but now I need to store the data I get with the first method into a variable so I can use it later on. How do I do that and also which of the two methods is better ?
I would use the second code if you already have jQuery included:
$.get('admin/user-count.php', function(data)
{
// Don't use "var" here, otherwise the variable won't be global!
myGlobalVar = parseInt(data, 10);
// Also possible: window["myGlobalVar"] = parseInt(data, 10);
});
If you want to use pure JavaScript:
var oXHR = new XMLHttpRequest();
oXHR.open("GET", "admin/user-count.php", true);
oXHR.onload = function(evt)
{
myGlobalVar = parseInt(oXHR.responseText,10);
}
oXHR.onerror = function(evt)
{
alert("Error!");
}
oXHR.send();
I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.