I want to pass the php variable inside the window.location javascript this is my php code and i am unable to do that.
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
try to set quotation marks
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'"</script>';
You are closing your quote in JS
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
Should be
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'</script>';
This will cause an error in JS on the client side, you could see this by pressing f12 and looking in the console log in the browser debugger. Your source code will look like this
<script>location.href = "reportConsumption.php?creategenReport="35"&sDate="...
//where this is a quoted block
"reportConsumption.php?creategenReport="
//and this is just chilling in space
35
//and then a new quoted block, etc.
"&sDate="
And you had this other (php syntax error) issue I took the liberty of fixing.
.$enddate;</script>';
Just in PHP you can redirect with
header("Location: $url");
But you have to be sure of 2 things:
You do not output "Anything" not even a line return before calling header
You call exit(); immediately after it. If you don't PHP will continue to execute the current script after it executes the redirect. Which is probably not desirable.
You are closing the double quotes too early. It should be close at the end of the URL. So you have a syntax error in your JavaScript:
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'";</script>';
Or separate using a variable to be more clear:
$url = 'reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate;
echo '<script>location.href = "'.$url.'";</script>';
You should not use double quote around the values for GET param
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.
'&sDate='.$startdate.'&eDate='. $enddate .'"';</script>';
Related
I want to read GDPR info from a file, then in PHP echo out a confirm box with the info, and I then set a cookie, using php setcookie.
I have trouble getting it to work:
$message = file_get_contents("my_gdpr_text.txt");
echo ('<script>confirm("'.$message.'")</script>');
The confirm box just does not pop up at all (not even a blank box). If I set the message value to "Oscar" or anything, it all works, so the problem must be the answer from file_get_contents. I know it is read correctly, by testing with print_r. Is some text formatting needed? Grateful for answer.
echo ('<script>confirm("'.$message.'")</script>');
The problem with this is that as soon as your $message variable contains any double apostrophes " your JavaScript breaks
For example
$message = 'Please click "OK" to confirm';
echo ('<script>confirm("'.$message.'")</script>');
Will become
<script>confirm("Please click "OK" to confirm")</script>
Which is of course invalid because of the mismatch of apostrophes.
You could do something like this.
$message = file_get_contents("my_gdpr_text.txt");
$message = json_encode($message);
echo ('<script>confirm('.$message.')</script>');
See also:
How do I pass variables and data from PHP to JavaScript?
How to escape string from PHP for javascript?
Also consider if you really need PHP:
How do I load the contents of a text file into a javascript variable?
I am using the following code in a seperate js file to use a php $_SESSION variable. However, I am getting a syntax error of SyntaxError: missing ; before statement. I have tried putting the ; in the usual place, but still the same.
What is the correct way to use a php session in js file. Thanks
var companycode = '<?php echo $_SESSION['ls_idcode_usr']?>';
There may be special characters in the value of the session variable. Use json_encode() to output a valid Javascript literal:
var companycode = <?php echo json_encode($_SESSION['ls_idcode_usr']);?>;
You can only use PHP in files ending in .php, otherwise the web server won't parse them looking for code to execute, and it'll just get passed down to the client.
You can certainly make a whatever.js.php file, where PHP will be involved in the production of the Javascript file that is passed down to the browser.
The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....
I was able to close the window. But with the timeout, it does not seem to work.
This test.php was called by the submit button's action on another window. If I remarked out all window closing script lines, then this "Sending ... This window will close itself after sending." will show up.
This echo "<script>window.close();</script>"; will close this window without showing any echo. The other 3 lines, all I see is a blank window and not being closed at all. Only on the Chrome I got a Server 500 error. I tried on Firefox, Safari, and Chrome.
Any suggestions?
test.php contains:
<?php
echo "Sending ... This window will close itself after sending.";
echo "<script>window.close();</script>"; // this line works
// echo "<script>setTimeout("window.close()", 5000);</script>";
// <script type="text/javascript">setTimeout("window.close();", 3000);</script>
// echo "<script type="text/javascript">setTimeout( function() { window.close(); }, 3000);</script>"
?>
<script type="text/javascript">setTimeout("window.close();", 2000);</script>
Tell me if this works, of course change 2000 to what you want ;)
You should pass a function to setTimeout().
Try this:
<script>setTimeout(function(){ window.close();}, 5000);</script>
UPDATE on your update:
Error 500 means "Internal server error", there is something wrong with your script, not the resulting page.
I assume that you are not posting the real script, but there is something else wrong in it besides what you output.
Did you really wrote double quotes inside PHP string?
Because what you are really doing is writing a compile error, something like that is illegal PHP code:
echo "something "quoted" something";
I still suggest you to write a proper function and not a string, but if you must, at least escape the double quote, or use the single quote to start PHP constant string if you don't have to parse variables in it.
echo 'something "quoted" something';//I prefer this
or
echo "something \"quoted\" something";
//but this still works, altough parser will try to find variable names
i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?