Having browsed SO for hours now and tried various proposed solutions to similiar problems so as having read the official jQuery Docs, I still can't get the following code to work and would appreciate any help and hints to what I'm doing wrong.
I basically try to pass a custom JSON-object using jQuery $.ajax post to a PHP AJAX-Handler, but my PHP-Script always tells me that the data is invalid and won't execute.
jQuery JavaScript Code:
function $('#linkButton').click(function(){
var latlng = '47.39220630060216,9.366854022435746';
var locationData = JSON.stringify({
from_mobile: '1',
location: latlng
});
$.ajax({
type: 'post',
url: 'ajax_handler.php',
data: locationData,
success: function (data) {
console.log(data); // returns 'Invalid location: ' from PHP
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ' ' + errorThrown);
}
});
});
Interestingly, when I log the "locationData" json-object, it looks just fine:
{"from_mobile":"1","location":"47.39220630060216,9.366854022435746"}
PHP AJAX-Handler Code 'ajax_handler.php':
$mob = json_decode($_POST['from_mobile']);
$loc = json_decode($_POST['location']);
if(!empty($loc))
{
echo myClass::theClassMethod($mob, $loc);
} else {
exit('Invalid location: '.$loc);
}
Can anyone here spot the issue why I can't read the JSON-Values in my PHP-Script? Any help is highly appreciated!