[英]executing php code within javascript on button click
Am trying to execute php code within javascript with button onclick event.我正在尝试使用按钮 onclick 事件在 javascript 中执行 php 代码。 I have two pages test.php and demo.php with button in each page.
我有两个页面test.php和demo.php ,每个页面都有按钮。 Now what I want to do is.
现在我想做的是。 when I click button in test.php , it should disable the button in demo.php and when test.php is reloaded,it should check the status of button in demo.php and according to that it should display it.
当我点击test.php 中的按钮时,它应该禁用demo.php 中的按钮,当test.php重新加载时,它应该检查demo.php中按钮的状态,并根据它应该显示它。
Now I have tried something which works fine as per the requirement.现在我已经尝试了一些可以根据要求正常工作的东西。 problem is that button on both pages doesn't work.
问题是两个页面上的按钮都不起作用。 code executes only when the page is refreshed.
代码仅在页面刷新时执行。
Here is the code that I have tried.这是我尝试过的代码。
first test.php首先测试.php
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function enable(){
var a='<?php
$_SESSION['demo']='enable';
if($_SESSION['btn_demo']=='enabled'){
$_SESSION['btn_test']='disable';
unset($_SESSION['demo']);
}
else {
$_SESSION['btn_test']='enable';
}
?>';
}
</script>
</head>
<body>
<input type="button" value="<?php echo $_SESSION['btn_test']; ?>" name="submit" id="submit" onclick="enable()" >
</body>
</html>
when I click on enable button in test.php , it should enable the button in demo.php .当我点击test.php 中的启用按钮时,它应该启用demo.php 中的按钮。
second demo.php第二个演示.php
<?php
session_start();
error_reporting(0);
?>
<html>
<head>
<script type="text/javascript">
function enable(){
<?php
$_SESSION['test']=$_SESSION['demo'];
if($_SESSION['test']=='enable'){
$_SESSION['btn_demo']='enabled';
} else
{
$_SESSION['btn_demo']='disabled';
}
?>}
</script>
</head>
<body>
<style>
</style>
<input type="button" value="<?php echo $_SESSION['btn_demo']; ?>" name="submit" id="submit" onclick="enable()" >
</body>
</html>
here the button should be enabled/disabled when button in test.php is clicked.当单击test.php 中的按钮时,应启用/禁用此处的按钮。 this both pages work fine when I refresh.
当我刷新时,这两个页面都可以正常工作。 doesn't work when either of the button is clicked.
单击任一按钮时不起作用。 how to solve this ?
如何解决这个问题? need help.
需要帮忙。
PHP executes before the javascript, so you cannot use in this way, You can call the file using AJAX PHP在javascript之前执行,所以不能这样使用,可以用AJAX调用文件
Try something like this:尝试这样的事情:
<script>
function enable(){
$.ajax({
type: "POST",
url: "setSession.php",
success: function(res) {
if(res==="Success"){
alert("Success!!!");
}
}
});
}
</script>
setSession.php设置会话文件
<?php
$_SESSION['demo']='enable';
if($_SESSION['btn_demo']=='enabled'){
$_SESSION['btn_test']='disable';
unset($_SESSION['demo']);
}
else {
$_SESSION['btn_test']='enable';
}
echo "Success";
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.