I'm trying to modify this http://www.w3schools.com/php/php_ajax_database.asp
I'm just using the HTML part of that ^. My php file only have
<?php
echo rand();
?>
And it works fine! It updates every time I switch something on the drop-down list.
But, I want it to run every second, but it won't work. This is what my HTML looks like:
<html>
<head>
<script>
function showUser() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/test.php?q="+str,true);
xmlhttp.send();
}
setInterval(showUser, 1000);
</script>
</head>
<body>
<div id="txtHint"><b>this will be updated</b></div>
</body>
</html>
The SetInterval won't run it. The php file is still only echo rand();.
It worked at some point but I screwed something up I believe. Thanks in advance.
setInterval() is likely running just fine, but showUser() is ending with an error since str is not defined. Check your JavaScript console for errors.
Either remove the reference to str, or define it somewhere.
try this:
setInterval(function(){showUser()}, 1000);
Replace
setInterval(showUser, 1000);
with
window.onload = function() {
setInterval(showUser, 1000);
}
Related
I am currently creating a website where we take the data of our most visited articles of our website and list them on a specific page.
Now, the way I am collecting the data is by using PHP and I am using JS to generate the result on my page. The thing is that the coding is working but it only works if the page link ends with .html (i.e. www.website.com/article.html) but it my page link is addressed like this: www.website.com/article, the results don't show.
I tried extending the link of my js (i.e. ../result.js) but that doesn't do anything.
If you could please help me figure this out, I'd greatly appreciate it!
Thanks!
Here is a sample of the js code:
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function mostVisitedExt()
{
loadXMLDoc('mostvisited.txt',function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
var res = txt.split('*&^');
document.getElementById("mostVisitedExt").innerHTML =
"<ul class='jrecent'><div class='jname'><p class='body'>"+res[0]+"</p> </div><div class='jcontent'><a href=http://"+res[0].toLowerCase()+".website.com"+res[20]+" class='body-link' target='_blank'>"+res[10].substring(2, res[10].length-2)+"</a><p class='body'>" +
res[21] + "</p></div></ul>" +
The mostVisitedExt function is the PHP file where it is getting the data from.
I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>
The reason I am asking this is because in one of my pages I link a javascript script and then when I try to run a function in the javascript file, it doesn't work.
This is weird because when I copy the exact same code from the script file and put it between the tags, the function then works fine.
Here is how I linked it:
<script src="../scripts/login.js" type="text/javascript"></script>
Here is how it is referenced:
<td><button type="button" onclick="login()">log in </button></td>
Here is the javascript file in case you want to see it:
function login()
{
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
username = encodeURICompenent(document.getElementById("username").value);
password = encodeURICompenent(document.getElementById("password").value);
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
If you attach an external JavaScript file to your document and it contains code that were not found inside any method written on function declaration syntax. those code would execute right after the browser parses the JavaScript file.
Ex.
function CallMe() {
console.log("I'm going to execute once callMe method is invoke");
}
console.log("I'm going to execute once browser parses the javascript file");
The login method on your case wont execute unless there is an event that triggers/invokes the click event of your button.
I am currently trying to refresh my page title every 10 seconds to ensure that the song info changes here:
But after the song changes, I am left with the same page title:
My JavaScript setInterval function isn't working correctly.
Here's my code (what should have worked):
<script type="text/javascript">
function songToTitle() {
document.title = "BDR | <?php echo $radio_info['now_playing']; ?>";
}
songToTitle();
setInterval(songToTitle, 10000);
</script>
<title>BDR | Loading Song Title...</title>
I don't really know what's up here.
It imports the song name correctly, but does not refresh.
Can anyone help me with this?
EDIT:
I tried using this too:
<script type="text/javascript">
function songTitle(){
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.title.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.x86cam.com/wp-content/plugins/songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
It won't even load the title.
You are refreshing a static piece of information. To get new information you must use AJAX.
PHP is loaded before your browser opens it.
In other words...
<?php echo $radio_info['now_playing']; ?>
turns into
'Song Name'
so when Javascript looks at it, it only sees Song Name and is none the wiser.
AJAX Reference - complete API reference with examples down the page for you to fork off of. Your responding page also needs to be programmed to respond correctly. Usually I suggest JSON but this you can probably just use a text transfer since it's so little data.
You can send the data using POST and the PHP file can have something like this at the top:
<?php if ($_POST['songcheck'] === true) { echo $songName; return; }; ?>
PS - refreshing every 10 seconds isn't very efficient. When the song is loaded, use the song length +2 or +3 seconds for the timer instead. Much better :)
You can't use that php code in there, it's not going to execute when the function runs because PHP ran at the server, the code is now running in your browser, so once the song changes, that string is still going to be the exact same string it was when the browser asked your server for that .html file
You'll have to ask your server what the current title is using an xhr call ever X seconds and then refresh the title based on that.
I guess you should do an ajax call or listen to a some event to retrieve updated song title. The document.title = "BDR | <?php echo $radio_info['now_playing']; ?>"; string is generated on initial page load.
Okay. I figured it out.
I put this in my code:
<script type="text/javascript">
function songTitle(){
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.title=xmlhttp.responseText;
}
}
xmlhttp.open("GET","songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
In my songTitle.php, it requests the song name from the Icecast server and displays only that.
Whenever the song changes now, it also changes the title.
I just had to integrate an XMLHTTPRequest like I did with how I displayed the song info on the page.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML;
}
}
xmlhttp.open("GET","cd_catalog.xml",true);
xmlhttp.send();
}
</script>
</head>
<body>
<script>
loadXMLDoc();
alert(xmlDoc)//dont work
if(xmlDoc){console.log("true")}
else(console.log("false"))
</script>
<div id="myDiv"></div>
</body>
</html>
If i try to access xmlDoc from within the body then the code does not work??Also i tried to know whether xmlDoc exist using if statement within the body like:
if(xmlDoc){console.log("true")}
else(console.log("false"))
but this also fails ,i m new to xmlDom so what mistake have i made above ?thanks
xmlhttp.open("GET","xmlhttp_info.txt",false);
sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
execute other scripts while waiting for server response &
deal with the response when the response ready
So this is the reason why ur alert within the body doesn't work since js will continue to execute code.
using async=false JavaScript will NOT continue to execute, until the server response is ready. If the server is busy or slow, the application will hang or stop.
Remember that async=false is not recommended, but for a few small requests this can be ok.