0

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);
}
asked Mar 8, 2016 at 7:08
2
  • What is the current response that you are getting? Please try logging the response from the server (php file) Commented Mar 8, 2016 at 7:14
  • Well @tai you are not supposed to use json_decode in 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, your default: gets executed in switch which is not providing JSON. Commented Mar 8, 2016 at 7:14

2 Answers 2

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'];

answered Mar 8, 2016 at 7:15
Sign up to request clarification or add additional context in comments.

Comments

1

Change $action = json_decode($_POST['action']); to $action = $_POST['action'];

answered Mar 8, 2016 at 7:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.