I have a variable localStorage.lastUpdate which stores a timestamp such as 1332237161. I need to pass that timestamp to the server which im trying to do by the line below with:
listener.php?q="+localStorage.lastUpdate
I also have another variable, localStorage.numUpdates that should receive the number of updates back from the server. I am confused whether I can use the below code with xml to run commands. Can my server side php file do something of the following
echo "localStorage.numUpdates=".$currentCount.";";
echo "localStorage.lastUpdate=".time().";";
where it would take affect on my localStorage variables in the javascript portion?
function contactServer()
{
if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlhttp.responseText;
}
}
xmlhttp.open("GET","listener.php?q="+localStorage.lastUpdate,true);
xmlhttp.send();
}
Any information would be helpful, thanks!
That won't work (and don't use eval()!).
But you can just output JSON in your PHP script:
echo json_encode( array('lastUpdate' => time(), 'numUpdated' => $currentCount) );
And in your JavaScript code:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = JSON.parse(xmlhttp.responseText);
localStorage["lastUpdate"] = result["lastUpdate"];
localStorage["numUpdated"] = result["numUpdated"];
}
Related
Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>
Hi I am new to this forum and hoping someone could help I have set a dropdown menu with option value dynamically pulling in from a mysql database. these values when selected use xml to return the ids and content according to whats been selected. In the url there is a variable which im having trouble getting PHP to create a session variable from it. Can this be done? Thanks
Thanks, this is the code where the url is set
function showUser(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("state").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("state").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send(null);
}
The php call '$id = $_GET['q'];
$_SESSION['q'] = $id;'
Do you mean this?
http://www.domain.com/?action=delete
$action = $_GET['action'];
$_SESSION['action'] = $action;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("abc=123");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
<?php if(isset($_POST['abc'])) {
$test123 = 'worked';
}
?>
}}
var worked = '<?php echo $test123;?>'; // <--- this is not working
How can I make this work? I don't receive the variable in PHP whether I use get or post methods.
You seem to have two fundamental misunderstandings. One is about AJAX, and the other is about client side vs. server side code. The latter is more important.
Server vs. Client
Essentially PHP and JavaScript are totally agnostic to each other. They do not run in parallel. In this context, they don't even run on the same machine (the PHP code runs on your server, the JavaScript on the user's computer). The only communication each script can do with the other is via HTTP.
It's test.php that needs to have the code
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
As long as test.php exists, this should work, but I'm thinking of it as a standalone script.
Using AJAX
Because of the asynchronous nature of AJAX and its HTTP dependency, you can't rely on when an ajax request will complete or even if it will complete. That is to say that any code that depends on the result of an AJAX call must be done in the ajax response callbacks.
That is, you would do something like this:
//php
<?php if (isset($_POST['abc']) { echo json_encode(array('success' => true)); }
//JavaScript
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (JSON.parse(xmlhttp.responseText).success) {
console.log('it worked!');
}
}
Additionally to what #Explosion Pills explained this means the php inside the ajax doesn't work as you expect.
At the place inside test.php put this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
echo $test123;
?>
Then in the code you have up there replace this:
<?php if(isset($_POST['abc']))
{
$test123 = 'worked';
}
?>
by:
var worked = xmlHttp.responseText;
and finally remove this last line:
var worked = '<?php echo $test123;?>';
And check out what happens.
I'm trying to pass a json string to php via ajax and php is not decoding it properly. a vardump in php after the decode always returns null. Can anyone tell me what I'm doing wrong. Big thanks!!!
var addObj= {"facility":"Baptist Medical Center",
"osb":"Jacksonville",
"office":"North Branch"};
var JSONstr = JSON.stringify(addObj);
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var rt = xmlhttp.responseText;
alert(rt);
}
}
xmlhttp.open("GET","jsontest.php?addObj="+JSONstr,true);
xmlhttp.send();
//php code in jsontest.php
<?php
var_dump(json_decode($_GET['addObj'], true));
?>
//php returns null
Try urldecodeing the parameter first:
var_dump(json_decode(urldecode($_GET['addObj']), true));
How do I send a javascript value to a PHP page, then reference that value IN the PHP page?
Assuming I have some sort of javascript AJAX solution such as this:
var id=5;
obj.onreadystatechange=showContent;
obj.open("GET","test.php",true);
obj.send(id);
I want to work with this particular id in the test.php. How can I do this?
In the javascript (I'm making a function so you can assign it to some other event)
//jQuery has to be included, and so if it's not,
//I'm going to load it for you from the CDN,
//but you should load this by default in your page using a script tag, like this:
//<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"><\/script>')
function sendValueGet(passedValue){
jQuery.get('test.php', { value: passedValue });
}
function sendValuePost(passedValue){
jQuery.post('test.php', { value: passedValue });
}
And then in your PHP:
<?php
if( $_REQUEST["value"] )
{
$value = $_REQUEST['value'];
echo "Received ". $value;
}
?>
Notice that I use "value" in the javascript "object" { value: ... } and in the PHP "REQUEST" variable $_REQUEST["value"]
If you want to give that a different reference name, then you need to change it in both places.
Using GET or POST is your preference.
Change your code to this:
obj.open("GET","test.php?id=" + id,true);
obj.send();
Then in test.php use $_GET['id']
//GET
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("GET","test.php?q="+id,true);
xmlhttp.send();
in test.php
$id=$_GET['q']
//POST
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
xmlhttp.open("POST","test.php",true);
xmlhttp.send("x=id");
in test.php
$id=$_POST['x']