Reputation: 619
I am trying to pass javascript Date object to php, but when i dump $_POST it returns empty array or string. I am doing this in same file, so in file.php are php code and javascript code. Also javascript shows that everything is correct because it alert in success function.
<?php
var_dump($_POST); //returns empty array
var_dump($_POST['zone']); //returns null
?>
<script type="text/javascript">
var date = new Date();
$.ajax({
type:'POST',
data: {zone : date},
success: function(data){
alert("test"); //this runs normally
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
</script>
Upvotes: 0
Views: 796
Reputation: 30903
Here is some code I tested on phpfiddle.org:
<?php
if(isset($_POST['zone'])){
// Only runs when there is a Post for 'zone'
//var_dump($_POST);
echo $_POST['zone'];
} else{
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
var date = new Date();
function postZone(){
$.ajax({
type:'POST',
data: {zone : date},
success: function(data){
console.log(data);
//alert("test"); //this runs normally
$("#zone").html(data.substring(data.indexOf("(")) + " is client TimeZone.");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
postZone();
</script>
Running Post.
<div id='zone'></div>
</body>
</html>
<?php
}
?>
Here is what I saw in the Post results:
array(1) {
["zone"]=>
string(57) "Mon Jan 18 2016 09:44:17 GMT-0800 (Pacific Standard Time)"
}
string(57) "Mon Jan 18 2016 09:44:17 GMT-0800 (Pacific Standard Time)"
Adding the if
statement helps to not confuse the results. Not sure how you'll do this if you're including this code. As I said in my comment, you;re not passing the Date object in your Post, so you should pass the specifics of what you need to PHP.
Edit
Updated code. You can now see the data
in console and the results show are:
Running Post.
(Pacific Standard Time) is client TimeZone.
This of course will be different for each client.
Upvotes: 3