简体   繁体   中英

How to use PHP variable value in javascript?

I'm using PHP, HTML and Javascript for my web app. Now I'm having a small issue with the following code.

$e=$_POST['users']; //$e should have either employee_id or a string "All"

Now depending on this value I've to redirect a HTML button to a specific page. In my case

if $e=="employee_id(or may be you could say that $e!="All")" then redirect the page to salary_report.php

and if $e=="All" then the page should redirect to salary_report_combined.php

My current button code is as follows :

<input type="button"  class="btn btn-primary" id="leavere" name="leavere" value="Back to Salary Report" onclick="location.replace('salary_report.php')"></input> 

So currently it is redirecting to salary_report.php file only. My issue is how should I apply a condition based on PHP variable value and execute the HTML code? Now could you help me in resolveing ithis issue. Thnks in advance.

You can do this:

if($e == "All"){
$redirectTo = "salary_report_combined.php";
}
else{
$redirectTo = "salary_report.php";
}

In your button:

<input type="button"  class="btn btn-primary" id="leavere" name="leavere" 
value="Back to Salary Report" onclick="location.replace('<?php echo $redirectTo ?>')"></input>

But I'd just create a link with the redirect page as href , like so:

<a href="<?php echo $redirectTo; ?>"> Back to Salary Report </a>

Hope this helps!

You can also use as below:

var $e = <?php echo $_POST['users'] ?>;

then use $e in condition.

As a solution to your problem you can store redirection url into a php variable and then access the value of php variable within javascript code snippet.

Eg

 <?php
 $redirection_url='';   //Initialzing of variable for redirection url
 if($e=='All')
 {
     $redirection_url='salery_report_combined.php';
 }
 else
 {
      $redirection_url='salary_report.php';
 }
 ?>

    <input type="button"  class="btn btn-primary" id="leavere" name="leavere" value="Back to Salary Report" onclick="window.location.replace('<?php echo $redirection_url; ?>')"></input> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM