I have a string returned by my PHP. I call the PHP script from $.ajax and try to put the string in a global variable for further manipulation. It says the variable is undefined. Could you help me ?
(I used dataType : "jsonp"
to avoid the error answered here Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource)
My javascript (Jquery, Ajax, ...) script
var my_data;
function get_my_data(){
$.ajax({
type: 'GET',
url: 'http://localhost:8012/My_PHP_scripts/test_1.php',
dataType : "jsonp",
crossDomain:true,
success: function (my_data){
console.log(my_data);
}
});
}
$( document ).ready(get_my_data);
PHP script
<?php
$user = 'JOHN';
echo json_encode($user);
?>
HTML Code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="MyJS.js"></script>
</head>
<body>
</body>
</html>
UPDATE
PHP Script
<?php
$name = 'JOHN';
$encoded2 = json_encode(array('name'=>$name));
echo $encoded2;
die( $encoded2 );
?>
JS script
var my_data;
function get_my_data(){
$.ajax({
type: 'GET',
url: 'http://localhost:8012/My_PHP_scripts/test_1.php',
dataType : "jsonp",
crossDomain:true,
success: function (result){
my_data = result;
console.log(my_data.name);
console.log(result.name);
}
});
alert(my_data.name);
}
$( document ).ready(get_my_data);