When I access call.php the variable name 'json' is not accessible to param.js as below:
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.