0

When I access the call.php page:

The variable name JSON is not accessible to param.js as below:

This is the code:

init.js

$("document").ready(function(){
    var data = {
      "action": "init"
    };
    data = $(this).serialize() + "&" + $.param(data);
    var json;
    $.ajax({
          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"]);
          }
    });
});

response.php

<?php
    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);
    }
?>

param.js

alert(json.favorite_beverage);

call.php

<html>
<head>
<title></title>
</head>
<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>
<body>
</body>
</html>

Did I miss something? Your help is kindly appreciated.

Jad Chahine
  • 5,158
  • 6
  • 31
  • 51
  • 1
    Learn what `asynchronous` word in `AJAX` mean. – u_mulder Jul 26 '15 at 16:48
  • @u_mulder - I resisted marking this one a dup because the dup does not explain both issues that are present in this question and I figured the primary goal here is to make sure an accurate and complete answer is provided. The first issue is a scoping issue. The second issue is an async issue. The dup only addresses the async issue. – jfriend00 Jul 26 '15 at 17:16

1 Answers1

2

You have several issues here.

  1. The variable json is declared within a function (inside the document.ready() callback) so it is only available within that function. You cannot access it from outside that function. That is how variable scoping works in Javascript.

  2. The ajax success handler is called sometime later (its asynchronous) so you cannot reliably set data from that and use it in other parts of your code. Any code that wants to use the result of an ajax call should be put into the success handler directly or in a function that you call from the success handler and then pass the data to that function.

Here's an example of the fix described in the second point:

$("document").ready(function(){
    var data = {
      "action": "init"
    };
    data = $(this).serialize() + "&" + $.param(data);
    var json;
    $.ajax({
          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"]);
                // call a function and pass it the ajax data
                myFunction(json);
          }
    });
});

// function located elsewhere
function myFunction(data) {
    // process the data here
}

FYI, you can learn a lot more about dealing with data returned from ajax calls here: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825