PHP refreshing using jQuery doesn't work in IE - javascript

I wanted to create a function in javascript/jQuery, that uses php script to refresh some data on my website. I'm using it like this:
function aval()
{
...
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d);
setTimeout(aval,200);
}
where #dost refers to some div at the end of my site
Then, my readadmin.php file looks like this:
<?php
$diff=$_GET["diff"];
$name = $_GET["date"];
$dtyg = $_GET["dtyg"];
$plik = fopen("myfile","r");
$tekst = fread($plik,filesize("myfile"));
fclose($plik);
$bookings = explode(";;;;", $tekst);
for ($i=0; $i<(sizeof($bookings)-1); $i++)
$data[$i] = explode(":::",$bookings[$i]);
echo "<script>";
// here I'm echoing some javascript code, that basically changes styles on my page,
//depending on my variables and data from a file
echo "</script>";
?>
Also, on my site (admin.php) I use login, so my site looks like this:
<?php
session_start();
if(!session_is_registered('pass'))
header('location: login.php');
?>
...html code
login.php:
..something not important, forms to get $_POSTs etc..
<?php
if ($_POST["login"] == $login && $_POST["pass"] == $pass)
{
session_register('login');
session_register('pass');
header("location: admin.php");
}
?>
Now, everything works great on Chrome or Firefox, but not on IE. When I change data in my file, IE doesn't react to this, and keep displaying old data. When I put session_start() and session_destroy() at the begining and end of readadmin.php, then data is refreshing properly, but whatever action I do, it logs me out. Nothing strange here, I start a new session every 200ms so I get kicked.
One more thing: when I'm changing data that goes to readadmin.php from site, it displays proper data back, and then immediately changes to old data.
Please help.

You can add timestamp to url so the browser will not cache the file:
$("#dost").load("readadmin.php?date="+dzien+"&diff="+diff+"&dtyg="+d+"&t="+Date.now());

Related

Why my confirm "alert" don't work on my code?

This is a page of a web app, and the job is simple:
I can see the "alert" that asks me whether I want to confirm or not. Based on the answer, I move to other pages.
If i sent my "if" cicle, the "alert" it's showed. This is the code
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>
So, before I answer your question; just a note. PHP and Js will run on different machines (even though you're testing it on your localhost, still consider them as different machines)
All PHP code is run, and executed on the backend before anything is sent to your browser, after which js code is executed. PHP does not understand JS syntax, it will only look at <? and ?> tags and execute everything inside them.
<?php
session_start();
include('../Model/gestoreAccessi.php');
include('connect.php');
?>
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = <?php header('Location: http://www.teamjg.altervista.org/Matteo/navbar.php');?>
else
<?php
session_start();
session_unset();
session_destroy();
header('Location: http://www.teamjg.altervista.org/Matteo/index.html');
?>
</script>
When this code is being sent by XAMPP (or whatever engine you use), the PHP is first executed which will make the code look like this:
// Session will be started
// contents of ../Model/gestoreAccessi.php will be copied and run
// contents of connnect.php will be copied and run
<script>
let result = confirm("Sei sicuro di voler procedere?");
</script>
<script>
if(!result)
result = //The header is already set
else
// Location is already set
</script>
So this is undefined behaviour as you are sending two header tags with different locations, my best guess is it will redirect to http://www.teamjg.altervista.org/Matteo/index.html.
One thing you could do as a hotfix is set window.location.href if you want to redirect your user to some other website. Read this.

How to refresh page and send variable

i have a php page where i press a button to edit on another page the mysql db records:
page name 'distintaBase.php'
here there is a list of names that are products name. Each product cointains a list of components.
When i press the edit button for one product i'm redirect to the new page 'modifDistBase.php'.
the $dist_base variable is passed to the new page. I use it on the page title
<h2>Modifica distinta base <?php echo $_GET['dist_base']; ?></h2>
and then to load the mysql db
<?php
$dist_base = $_GET['dist_base'];
$sql = "SELECT $dist_base.Id, $dist_base.Designator, $dist_base.Quantity, $dist_base.Description, $dist_base.Package,
$dist_base.Manufacturer, $dist_base.Pn_Manufacturer, $dist_base.Pn_Utterson, $dist_base.Mounted
FROM $dist_base";
?>
pressing ADD button i add a new component
if(isset($_POST['add_item'])){
$designator = $_POST['designator'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$package = $_POST['package'];
$manufacturer = $_POST['manufacturer'];
$pn_manufacturer = $_POST['pn_manufacturer'];
$pn_utterson = $_POST['pn_utterson'];
$mounted = $_POST['mounted'];
$sql = "INSERT INTO $dist_base (designator,quantity,description,package,manufacturer,pn_manufacturer,pn_utterson,mounted)
VALUES ('$designator','$quantity','$description','$package','$manufacturer','$pn_manufacturer','$pn_utterson','$mounted')";
if ($conn->query($sql) === TRUE) {
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
} else {
echo "Errore: " . $sql . "<br>" . $conn->error;
}
}
there is something wrong probably on the javascript.
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
the new component is added to the database (for example with #5 id) but do not appear on the page modifDistBase.php
if i press refresh on the browser or f5 now i can see the new component (#5 id) but on the database a new one is added #6 with the same items as #5
PS
- header is already sent by menĂ¹ page
- have tried window.location.href with same result
Why don't you try with:
header('Location: modifDistBase.php?dist_base='.$dist_base);
instead of echo javascript you can redirect immediatelly to the page + the variable
there are some thing to fix on your code
Note the javascript you output with
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
will be precisely
<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>
Without checking the correctness of the js related to your goal, it's immediate to see you should write instead
echo '<script>window.location.replace("modifDistBase.php?dist_base="' . $dist_base . '")</script>';
to inject the php value into the javascript string.
(you've also forgot a double quote b.t.w)
If you have doubts regarding your javascript, you can inspect the page on the browser and look at it (right click and "inspect element" or "analyse element").
Mind it is not recommended that you take the user input and use it as it is in an SQL instruction. You should do some sanification and use a prepared statement or escape the values before putting them in the sql.
That said, the javascript redirection you do looks a bit odd, maybe you can redirect from the php script without asking the client to do so. Look at the header php function for instruction about redirection done server side.

How to connect between the sessionStorage in PHP to JS

I am trying to transfer data in my PHP (html) page, befor the HTML is loaded, so I will be able to deal with it after the page is loaded in my JS file.
my php look like this:
<?php
/*some php code*/
$dataFromDataBase = "..";
session_start();
$_SESSION['data'] = $dataFromDataBase;
if(isset($_SESSION['data']))
echo $_SESSION['data'];
else
echo "<br>False";
?>
<html>
<!--My Html code..-->
</html>
the "if" condition is there now to check if the session was created in the php.
now it echo me the data, so it's meen the session exist.
my JS look like that:
if(sessionStorage.getItem("data")){
//do some thing..
}else{
alert("the data isn't set.");
}
and the data isn't exist... I've tride to alert the data, and it send me "null"..
they offered me to output into JS directly like that:
<script>
var fromserver="<?php
/*some code.. */
echo "**BIG DATA**";
?>";
but it is just untidy code.. and the data is pretty big so I can't use coockies
$_SESSION and sessionStorage are completely different.
sessionStorage saves data like $_SESSION except a sessionStorage variable is set on the client's side. $_SESSION is like sessionStorage so I see your misunderstanding, however, this sets data on the server-side and does not cross over to sessionStorage.
If you really need that $_SESSION data in sessionStorage, you can echo a script which sets the sessionStorage to your $_SESSION data. Here's a very simple example below.
<?php session_start;
$_SESSION['data'] = "yourdata";
echo '<script> sessionStorage.setItem("data", "' . $_SESSION['data'] . '");</script>';
//Display 'data'.
echo '<script> alert(sessionStorage.getItem("data")); </script>';
EDIT: To make it more clearer, notice how $_SESSION is done in PHP (server-side) and sessionStorage has to be set in JavaScript with the <script> tags. Below is a solution to your problem.
<?php
/*some php code*/
$dataFromDataBase = "..";
session_start();
$_SESSION['data'] = $dataFromDataBase;
if(isset($_SESSION['data']))
{
echo '<script> sessionStorage.setItem("data", "' .$_SESSION['data'] .'");</script>';
}
else
{
echo "<br>False";
}
?>
<html>
<!--My Html code..-->
</html>
Creating executable JS code from user provided data is a major security issue, so you should avoid the statements like var someJsVar = '<?= $somePhpVar;?>;'. Injecting malicious code could be a simple as '; malicious-code-here //
https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
https://www.owasp.org/index.php/XSS_Attacks
It would be more secure to have your page make an API call on page load, which would return your data for sessionStorage encoded as JSON. This way the browser will see a variable containing the user data, and not the raw data itself.
#Initial page
<body>
<script>
$.GET("/session-storage.php").success(function(response){
sessionStorage.setItem("data", response);
});
</script>
</body>
#API Call (session-storage.php)
<?php
$dataFromDataBase = "..";
echo json_encode($dataFromDataBase);
?>
you can take data from php variable and use it in JS.. like this
var sessionData = <?php echo $_SESSION['data'];?>
if (typeof sessionData != "undefined" && sessionData == null){
//do some thing..
}else{
alert("the data isn't set.");
}

Header location is not working on live server

I Have one registration and payment page. program flow is like registration > confirmation > payment. After validation and calculation in registration page need to go to confirmation page.
My code is
<?php
ob_start();
session_start();
include("header.php");
include("ini.php");
date_default_timezone_set('Asia/Brunei');
header('Cache-Control: max-age=900');
if (isset($_POST['submit'])) {
$error = 0;
//validations
if ($error <= 0) {
//do some calculation
header('location:confirm.php');
}
}
<?php
ob_flush();
?>
Control entered in to if ($error <= 0) clause, but stay on the registration page.
I tried many ways like
header('location:confirm.php', true, 302);
instead of
header('location:confirm.php');
removed
ob_start() and ob_flush()
add exit() after header()
then it goes to blank page.
Also try to use
echo '<script type="text/javascript">';
echo 'window.location.href="confirm.php";';
echo '</script>';
Then the control goes to confirmation page but url seems to be as registration.php
But header('location:confirm.php'); is working fine in my local server. Anybody please help me to resolve this issue.. Is there any alternate way for header(). Looking forward to you guys.. Thanks
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
Also try to change header('Location:confirm.php');
(Note L is capital since its work in your local server may be problem with strict php type try this once)
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'confirm.php';
header("Location: http://$host$uri/$extra");
use ob_end_flush() at the end. This should work like charm.
i had the same issues for years but today i discovered that u don't have to have any html or blank space before the header word .Try it out

Reload a javascript using jquery

I have made a PHP file that shows up a session meter for Joomla's frontend using JavaScript. I have also made an other PHP file that shows the user's details and it reloads using jQuery. What I want to do is, when I press jQuery's reload button, JavaScript session meter reload too.
Session Meter PHP:
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access');
$document = & JFactory::getDocument();
$document->addStyleSheet('***/***/session_meter.css');
include('***/***/scripts.php');
$document->addScriptDeclaration($javascript);
$output = array();
$session = & JFactory::getSession();
$expire = $session->getExpire();
$output[] = '<span id="log_res" class="">'.$expire.'</span>';
foreach ($output as $item){echo $item;}
?>
Session Meter javascript (part of it):
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access');
$javascript = ' var timer_start =$time(); '."\n";
$javascript .= 'blah blah blah...
?>
User Profile JQuery script (part of it):
<?php // NO DIRECT ACCESS
defined('_JEXEC') or die('Restricted access'); ?>
<script>
var $JQ_ = jQuery.noConflict();
$JQ_(document).ready(function(){
$JQ_("#refresh_button").click(function(){$JQ_("#r_points").load('index.php #r_points').fadeOut(1000).fadeIn(1000);});
});
</script>
I am trying to do something like this:
$JQ_("#refresh_button").click(function(){
$JQ_("#log_res").load('index.php #log_res').fadeOut(1000).fadeIn(1000);
});
but it only reloads session meter's span and not its JavaScript!
Any idea?
i don't know what can be done with php...but things you can do are:
Save In local storage (the progress)
Put reloading part in iframe so parent doesn't load again
Wrap Js meter part into function and call it at the top/onload event, so when page reloads it gets called too.
Use eval to call javascript that is in string form

Categories

Resources