on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:
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("dataSuccess").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php",true);
xmlhttp.send();
In the getData.php file, data is gathered from MySQL and put in JS-arrays:
var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");
And finally, store the data in my js arrays into LocalStorage:
var guestDataCols = new Array();
guestDataCols = guestData[0].split(",")
var arrayIndex=0;
for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
{
localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
}
EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question
$('#dataSuccess').load('getData.php'); //instead for the AJAX code
but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?
JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.
I think you're looking for jQuery.getScript
Related
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>
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.
I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.
I have use Ajax and jquery for get data from database and send data, but when we use ajax or jquery methods, web page source view ,we can see details like below;
Ajax
<script type="text/javascript">
function showUser()
function showUser()
{
var str = document.getElementById('txtusername').value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="<span style='color:#FFF;font-size:10px;'>Enter username</span>";
return;
}
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","chkusername.php?q="+str,true);
xmlhttp.send();
}
</script>
In here you can see the get method and what are the sending values and also more things. I want hide these thing from source view, help me ..
You can't. Anything on the client side (HTML, CSS, JavaScript) is free for the user to see.
That's why anything security-related is on the server side, where it can be trusted (for the most part).
It's not a security risk if the user knows that to log in you go to /chkusername.php?q=username (or whatever). It is one, however, if you don't properly sanitise the input.
I have a Javascript game running within a HTML5 canvas. Now I'd like to pass on a variable that is stored in an object in PHP to my program. What I'd like to have would be a function in my js like getVariable = function(){script that gets the variable from PHP and returns it as a string}
Any hints?
#Valentin - simply use javascript ajax call(Or jquery call if you like) to get the values from the php script. If your game has different values for different players you can start a session and persist the values across many calls to the script.For example -
Let say you want to get the health of the player from player.php which looks like
session_start();//start the session
if(!isset($_SESSION['health']))
$_SESSION['health'] = $var;//If there is no value for player health in the session
//initialize the default value
switch($_GET['x']){
case 'health' :
echo $_SESSION['health'];
break;
default :
echo $var;
break;
}
?>
and the corresponding pure javascript would be -
var health;
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)
{
health=xmlhttp.responseText;
}
}
xmlhttp.open("GET","player.php?x=health",true);
xmlhttp.send();
You could do the same in a much simpler fashion using the awesome jQuery -
var health;
var reqData=["x" : "health"];
var xhrObj = $.get("player.php",x)
.done(function( response ) {
health=response;//The echo text from server
})
.fail(function() {
alert('error');
});
You can learn more about jquery and ajax here -->
jQuery API
www.w3schools.com/ajax/ for the ajax tutorial
Javascript and the browser don't care what language you're using on your server to generate the HTML/JS, all they care about is what is generated in the end.
To do what you're thinking, you'd have 2 ways to do it:
Print the contents of the variable to the page when initially generating it.
Use an AJAX call to a script on your server that echo's the value, then parse it in JavaScript. If you do this, though, you'd have to use the session or a database, or another means of keeping state between pages.