I'm trying to work through a JSON to PHP and back example but can't figure out why I cannot get a success response to occur when setting dataType to json. Any help as to what I need to do and where I can find a good tutorial would be greatly appreciated. Thanks!
var selected = $('#getID').val();
$.ajax({
url: 'includes/ajaxCalls.php',
type: "POST",
data: {action: 'test', id: selected},
dataType: 'json',
success: function (results) {
alert("completed");
},
fail: function (data) {
console.log('Could not get posts, server response');
}
});
PHP
if (isset($_POST['action']) && !empty($_POST['action'])) {
$action = json_decode($_POST['action']);
switch ($action) {
case 'test' : test();
break;
case 'blah' : blah();
break;
default:
echo "hello";
}
}
function test() {
header("Content-Type: application/json", true);
$array = array(0,1,2,3);
echo json_encode($array);
}
2 Answers 2
Some things you need to fix on your PHP code,
1) You don't have to call json_decode on $_POST['action'], you have a string in action variable so you can simply call $_POST['action'], don't have to pass it to json_decode. json_decode is used when the data is a JSON string which is then converted to an array in PHP.
2) Don't set the header in your test() you are already requesting for JSON data from your AJAX call, and from your server i.e PHP you are echo-ing JSON back so you don't have to explicitly set the header here.
Change $action = json_decode($_POST['action']); TO $action = $_POST['action'];
Comments
Change $action = json_decode($_POST['action']); to $action = $_POST['action'];
json_decodein this$action = json_decode($_POST['action']);line. Because the AJAX request is fetched as Array itself so$_POST['action']will solve your purpose. Due to this, yourdefault:gets executed in switch which is not providing JSON.