Jason Krs Jason Krs - 6 months ago 21
Javascript Question

jquery ajax request result undefined

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);

Answer

You are not getting a valid JSON because your PHP Code was only encoding a plain string... why don't you try something like this in your PHP Script instead?

Your JS could be better like this:

function get_my_data(evt) {
    $.ajax({
        type: 'POST',
        url: 'https://evoq.ch/aurora/test.php',
        dataType: "json",
        crossDomain: true,
        success: function(my_data) {
        alert(my_data.name);
        }
    });
}

Confirm this HERE.

<?php   
    header('Access-Control-Allow-Origin: *');   //<== ALLOW ACCESS TO ALL...
    header('Content-Type: application/json');   //<== TELL HEADER TO DELIVER JSON-TYPE DATA 

    $user = array('name'=>'JOHN');
    die( json_encode($user) );     

Now you'd have a valid JSON Data and you can access it like so:

    my_data.name;    // WILL OUTPUT:  JOHN

NOTES:

    <?php 
        $name     = 'JOHN';
        $encoded1 = json_encode($name);    
        die( $encoded1 );         //<== RESULT: 'JOHN'           |==>[INVALID JSON - STRING]

        $name     = 'JOHN';
        $encoded2 = json_encode( array('name'=>$name) );    
        die( $encoded2 );         //<== RESULT: {"name":"JOHN"}  |==>[VALID JSON]

Test it out HERE