When I access call.php the variable name 'json' is not accessible to param.js as below:


    var data = {
      "action": "init"
    data = $(this).serialize() + "&" + $.param(data);
    var json;
          type: "POST",
          dataType: "json",
          url: "response.php", //Relative or absolute path to response.php file
          data: data,
          success: function(data){
                json = JSON.parse(data["json"]);


    if (is_ajax()) {
        if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
            $action = $_POST["action"];
            switch($action) { //Switch case for value of action
               case "init": test_function(); break;
    function is_ajax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    function test_function(){
        $return = $_POST;
        $return["favorite_beverage"] = "Coke";
        $return["favorite_restaurant"] = "McDonald's";
        $return["json"] = json_encode($return);
        echo json_encode($return);




<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript" src="param.js"></script>

Did I miss something? Your help is kindly appreciated.

Member Avatar

data inside the success will not be visible to outside. It's not a good idea anyhow as ajax is asynchronous and the call could still be in progress when the alert is fired. Why not move the alert to the success?

Have a look at .done()

It works:

    request.done(function (data) {

However when I attempt to access the data outside the function:

    var jsonMsg;

    request.done(function (data) {
        jsonMsg = data;


It doesn't work.

Member Avatar

This suffers from the same issue from Ajax being asynchronous. DO not be tempted to set ajax to async:false though as your whole system may hang.

Is there any reason why you need this outside the done or success functions? Remember that you can run outside functions from within these:

request.done(function (data) {

function doSomething(data)
    alert('I realise that this may be the opposite of what you were asking for, but this is painless and relatively easy ' + data);
commented: good advice, +1 +12