I have two pages. On page one, called test1.html, I try to retreive the users timezone. I would like to send it of to a php page called test2.php and load that page instead of test1 with the variable (timezone). This is the code.
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test2.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
});
});
</script>
Test2.php
<?php
if(isset($_POST['timezone']))
{
$tz = $_POST['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>
On pageload of test2.php, I only ever get the 'Fail!' message. The jquery and php part do work correct as I tested it with an alert call in test1.html to log the reponse from the php page. It gave the response I expected.
I think I lose my variable when the code is executed to reload test2.php in the same window. I just don't know how to bypass this problem. I want to use POST rather then GET if possible.
Any help greatly appreciated.
Little note: Idealy I want to use this javascript and the php to be on the same page but the 'problem' there is that php is of course executed serverside first and then it runs je js client side afterwards...
An alternative solution that still allows you to use POST, which you said you'd like, is to store the information in a session variable. The session is an object that can be used to store values between requests. See http://php.net/manual/en/book.session.php
Test1.html:
<script type="text/javascript">
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
$.ajax({
type: 'POST',
url: 'test2.php',
data: {'timezone': timezone},
cache: false,
success: function(){
setTimeout(function () {
window.location = 'test3.php';
}, 3000); }
});
});
</script>
Test2.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Store posted timezone in the session, which will be available in future calls
if(isset($_POST['timezone'])) {
$_SESSION['timezone'] = $_POST['timezone'];
}
else {
echo "Fail!";
}
?>
Test3.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_SESSION['timezone']) {
echo "Your timezone is " . $_SESSION['timezone'];
} else {
echo "Fail!";
}
You are misunderstanding the flow of how your client and server are interacting with each other. Your code sends a POST request to test2.php, and THEN (in the success callback that triggers when your request is done) it redirects to test2.php. The first time test2.php is run, it gets the timezone POST variable, but the second time it doesn't. You can see this by looking at network traffic in your browser's developer tools - you'll see two requests to test2.php. The first will return "Timezone is...", and the second (which your browser is showing) says "Fail!"
There are different ways to get what you want, but the easiest would be to skip the AJAX altogether and just send the timezone along with the redirect:
$(document).ready(function() {
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.
// This redirects to test2.php while setting a GET parameter called "timezone"
window.location = 'test2.php?timezone='+encodeURIComponent(timezone);
});
<?php
if(isset($_GET['timezone']))
{
$tz = $_GET['timezone'];
echo "Timezone is " .$tz;
}
else {
echo "Fail!";
}
?>
Related
So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload();</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);
i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query
little issue over here.
I have a php function that is called via AJAX and looks like this:
function processActiveDirectory(){
$var = new GetLDAPUsers;
echo "Getting Users from Active Directory.... <br />";
$adusers = $var->getAllUsers();
echo "setting up images.... <br />";
// processing more stuff
echo "finished";
}
I'm trying to get a "live- log" echo. Meaning before every step the echo should output to a Log area, one step after another. So the user knows what's going on.
But the Problem is, that the log doesn't appear during the process, it just fills in at the whole text at the end of the process. Everything else works fine. The Log just doesn't appear at runtime, but after the function is finished it appears at the right position.
My AJAX call:
jQuery(document).ready(function($) {
$('#lii-form').submit(function() {
data = {
action: 'lii_map_images'
};
$.post(ajaxurl, data, function(response){
$('#lii_log').html(response);
});
return false;
});
});
This is how it's build:
Edit
Other than in this thread I'm already using an ajax call, to call the function. It's within the called function that I'm echoing stuff...
Edit 2
I'm using wordpress
Sorry I can't offer more informations, because of enterprise restrictments.
This is a short over-view on your need. Please develop further with this idea.
This uses two AJAX calling - one for the main process and other for progress:
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//Start the main process
$.ajax({
url: 'main.php',
success: function(data) {
}
});
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
$("#progress").html(data);
if(data != "finished"){
getProgress();
}
}
});
}
//Start the progress section
getProgress();
</script>
<div id="progress"></div>
main.php
<?php
$arr = ['Getting Users from Active Directory....','setting up images....','finished'];
foreach($arr as $value) {
session_start();
$_SESSION["progress"]=$value;
session_write_close();
sleep(1);
}
progress.php
<?php
session_start();
sleep(1);
echo $_SESSION["progress"];
So your processActiveDirectory will come under Main.php and echo should be replaced with SESSION variable
I think there is no need in such thing as LOG process WITH AJAX. AJAX is too heavy thing and it could be a bad design if you want it. It's better to use web sockets or not use at all
I have the message-block in the header of my site. When a user clicks "close msg", the message should disapear and can't be seen during current user session.
So I decided to use jQuery Ajax:
$('#lang-msg .close').on('click', function(event) {
event.preventDefault();
$.ajax({
url:"remlmsg.php",
type:"POST",
data:"id=2,myajaxquery=true ",
success:function(html){
console.log(html);
$('#lang-msg').fadeOut(300,function() {
$(this).remove();
})
}
})
})
And in remlmsg.php I have only code, which defines new session variable:
$_SESSION['langmsg'] = 'hide';
echo $_SESSION['langmsg'];
In the header.php file I check if $_SESSION['langmsg'] is undefined.
if (!isset($_SESSION['langmsg'])) {
if ($sLanguage == 'ru') {
echo '<script type="text/javascript">
$( function() {
showLangMessage("en");
})
</script>';
}
}
And it says always true! But when I print request data in ajax function it displays 'hide'.
Explain to me, please, where I did mistake.
P.S.
Tested on local server (latest WAMP)
You need to have session_start() declared first. Otherwise you'll only edit a local variable that isn't stored anywhere.
Actually the problem you're having is that ajax calls will have a different session id, which has to do with the headers sent/received by both sides.
Try generating some javascript with PHP like:
var phpSessionId='<?=session_id()?>';
then in your remlmsg.php add this to the very top:
if(isset($_POST['session-id'])) session_id($_POST['session-id']);
session_start();
Finally in your ajax call use:
data:"id=2,myajaxquery=true,session-id=" + phpSessionId,
That should solve your problem.
I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.