Why doesn't PHP find my index, myPostData
?
jQuery/AJAX
$('a').on("click", function(){
$.ajax({
type: "POST",
url: "../image_view.php",
data: {myPostData : {"lastName":"Sperrow", "firstName":"Jack"}}
dataType: "json"
})}
});
PHP
<?php
var_dump($_POST['myPostData']);
?>
And I get the following error:
( ! ) Notice: Undefined index: myPostData in /var/www/image_view.php on line 7
Call Stack
# Time Memory Function Location
1 0.0001 228280 {main}( ) ../image_view.php:0
null
var_dump($POST) when
data: {myPostData : JSON.stringify({"lastName":"Sperrow", "firstName":"Jack"})}
output
array (size=0)
empty
var_dump($POST) when
data: {myPostData : "something"}
output
array (size=0)
empty
The reason is because, for a content type of application/x-www-form-urlencoded
, jQuery typically serialises the line below:
data: {myPostData : {"lastName":"Sperrow", "firstName":"Jack"}}
as
myPostData[lastName] => Sperrow
myPostData[firstName] => Jack
What would fix your problem is:
data: {myPostData : JSON.stringify({"lastName":"Sperrow", "firstName":"Jack"})}