[英]how to pass js variable to php via ajax
Hello I am new to js and I stuck on the problem about passing variables to php via ajax. 您好,我是JS的新手,但我坚持通过ajax将变量传递给php的问题。
<script>
$date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
And below is my code in record.php file. 下面是record.php文件中的代码。
<?php
session_start();
if(!empty($_POST['date'])){
//$hello = 'hh';
$_SESSION['date'] = $_POST['date'];
echo($_SESSION['date']);
}else{
echo "its empty(var)";
}
?>
Page always print out "its empty(var)" and I checked console, it shows "successfully"... I already stayed on this problem for several hours and looked for a lot of similar post, but I still can't find where is the problem. 页面总是打印出“其empty(var)”,我检查了控制台,显示“成功” ...我已经在这个问题上待了好几个小时,并且寻找了很多类似的帖子,但是我仍然找不到哪里是问题。 Can anyone have a look at it?
有人可以看看吗? I also already loaded the jQuery library.
我也已经加载了jQuery库。
you ar mixing js variable with php variable, js variables are declared with var
and php variables are declared with $fieldname
您将js变量与php变量混合在一起,js变量用
var
声明,而php变量用$fieldname
声明
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>
if you want a PHP variable insite javascript you should define php variable first then asign it into js. 如果您想要一个PHP变量内置javascript,则应先定义php变量,然后将其分配给js。
<?php $date = "123"; ?>';
<script>
var date=<?php echo $date; ?>';
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
Hope it wil helps you. 希望它能对您有所帮助。
You cant mix server (php) and client (js) 您不能混合使用服务器(php)和客户端(js)
you might to this 你可能会这样
<?php $var = 0?>
then in html you create 然后在html中创建
<input id="something" type="hidden" value="<?php echo $var?>">
then you get that value via 然后您通过获得该值
document.getElementById("something").value;
You are declaring $date
and pass in your ajax as date
. 您声明
$date
并将ajax传递为date
。
Try this: 尝试这个:
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.