0

Everything was working a couple of days ago, but all of a sudden it is no longer working. I think I have tried everything, but no change, so coming to SO as last resort!

I have gone through this article and checked my php.ini file, and the post_max_size is set to 8M

Ajax request from JS:

$.ajax({
    url: "getFromDB.php",
    type: "post",
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}, // Tried with and without
    data: { action: "getRouteList" },
    success: function(obj){
        alert("Yay!");
    }
});

myPage.php

// From this SO answer: http://stackoverflow.com/a/14794856/4669619
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

var_dump($rest_json);
var_dump($_POST);

getRouteList();                         // Works

if (isset($_POST["action"]) && !empty($_POST["action"])) {
    file_put_contents('function_result.txt', "Action: Set" . PHP_EOL . PHP_EOL, FILE_APPEND);
    $action = $_POST["action"];

    if ($action == "getRouteList") {
        getRouteList();                 // Doesn't work (b/c $_POST isn't set)
    }

} else {
    file_put_contents('function_result.txt', "Action: Not set!" . PHP_EOL . PHP_EOL, FILE_APPEND);
}

var_dump output:

string(19) "action=getRouteList"    // $rest_json
NULL                                // $_POST // NULL b/c of '='?

function_result.txt output

Action: Not set!

Firebug info:

enter image description here enter image description here

Ali
  • 558
  • 7
  • 28
  • For `$_POST` you defintiely don't want to set contenType as json or use `json_decode`. If you do want to send json you need to stringify the data object .. jQuery won't do that for you – charlietfl Mar 26 '16 at 19:56

1 Answers1

1

You are mixing up contentType approaches

if you want to continue using json you need to stringify the data sent and leave php the same

var json = JSON.stringify({ action: "getRouteList" });
$.ajax({
    url: "getFromDB.php",
    type: "post",
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}, // Tried with and without
    data: json,
    success: function(obj){
        alert("Yay!");
    }
});

Or to send as form encoded then remove the header for Content-Type and remove the file_get_contents() and json_decode() in php and $_POST would be used like any normal form submit

charlietfl
  • 170,828
  • 13
  • 121
  • 150