Reputation: 57
Hello I am new to js and I stuck on the problem about passing variables to php via ajax.
<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.
<?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. Can anyone have a look at it? I also already loaded the jQuery library.
Upvotes: 0
Views: 3968
Reputation: 1477
You are declaring $date
and pass in your ajax as 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>
Upvotes: 0
Reputation: 369
You cant mix server (php) and client (js)
you might to this
<?php $var = 0?>
then in html you create
<input id="something" type="hidden" value="<?php echo $var?>">
then you get that value via
document.getElementById("something").value;
Upvotes: 0
Reputation: 980
if you want a PHP variable insite javascript you should define php variable first then asign it into 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.
Upvotes: 0
Reputation: 27533
you ar mixing js variable with php variable, js variables are declared with var
and php variables are declared with $fieldname
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>
Upvotes: 2