-1

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);
Community
  • 1
  • 1
Jason Krs
  • 704
  • 2
  • 9
  • 30
  • Try `dataType : "json"` – Akhilesh B Chandran Jun 05 '16 at 12:58
  • remove the localhost part from the url. Browsers are strangely reaacting to this – Toumash Jun 05 '16 at 13:02
  • @AkhileshBChandran If I try that I get the following error http://stackoverflow.com/questions/23959912/ajax-cross-origin-request-blocked-the-same-origin-policy-disallows-reading-the I used jsonp as suggested there – Jason Krs Jun 05 '16 at 13:26
  • @Toumash hmm I don't think this is a good idea. this address is the URL of my script in my xammp Apache server. Please see this http://stackoverflow.com/questions/37632325/php-101-how-to-call-an-external-php-file-with-action/37633316#37633316 – Jason Krs Jun 05 '16 at 13:28
  • @JasonKrs You can either use `echo $encoded2;` or `die($encoded2);` but not both at the same time..... – Poiz Jun 05 '16 at 13:54
  • @JasonKrs By the way, why not use POST in your AJAX. Check out a Live Test here: https://jsfiddle.net/1oemmv7h/ – Poiz Jun 05 '16 at 14:07
  • @Poiz This is where it all started (before I arrived here). My web server in on my local machine. So the url I'm using is `localhost:.....` Whith that kind of URL and datatype ='json' I get and error http://stackoverflow.com/questions/23959912/ajax-cross-origin-request-blocked-the-same-origin-policy-disallows-reading-the The only way to fix that is to put jsonp as data type. Now it seems that it's jsonp that bwill raise the `missing ; before statement` php error – Jason Krs Jun 05 '16 at 14:59
  • @JasonKrs Why don't you simply add `header('Access-Control-Allow-Origin: *');` at the top of your PHP File? It will also work JSON too.... The Answer we Posted below has now been updated to take that into consideration.... – Poiz Jun 05 '16 at 15:05
  • @Poiz Problem Solved. I really want to understand what happened here. Could you redirect me to somthing to read or a quick explanation will be great (so far I understood that PHP wasnt returning JSON encoded results and that, i was not allowing local POST request) – Jason Krs Jun 05 '16 at 15:13
  • 1
    @JasonKrs The 1st issue was that you tried to echo a String instead of JSON. You solved that by json_encoding a key-value Array `json_encode(array('name'=>$name)); `. Then the next issue was Sandbox related. Bcos of the nature of your URL, Access was denied when you sent an AJAX Request to the PHP Script. `header('Access-Control-Allow-Origin: *');` solved that part. You can read more here: http://jqfundamentals.com/chapter/ajax-deferreds – Poiz Jun 05 '16 at 15:21

2 Answers2

2

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://some-domain.ch/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

Poiz
  • 7,611
  • 2
  • 15
  • 17
  • wow now I get a php error : missing ; before statement. In the console it refers to ` {"name":"JOHN"}` Weird since there is nothing before that line. Also my_data is still undefined. I don't understand why this php error arises. Non sense....I used the $encoded2 part (just those 3 lines) – Jason Krs Jun 05 '16 at 13:37
  • @JasonKrs please just update your post with your changes in order to we will be able to help you. – Nico Jun 05 '16 at 13:43
  • @Poiz The php is bugging me mate lol (I think my browser is crazy). I only copied pasted what you gave me (I'm not even using my own arrays yet )...I still get the same errors ; that `missing ; before statement` and `my_data` is undefined. Please see the updated scipts in my OP – Jason Krs Jun 05 '16 at 13:52
  • @JasonKrs Now we have an encoding problem too, if you are returning json string bases result, then you need to return the content-type header. To do this justo append header("Content-type:application/json"); before $name ... assingment and use "json" in the ajax's dataType – Nico Jun 05 '16 at 14:02
  • @Nico I can't use "json" as datatype because it raises an error : http://stackoverflow.com/questions/23959912/ajax-cross-origin-request-blocked-the-same-origin-policy-disallows-reading-the Also I'm not just returning a strin but a PHP array object...kinda difficult – Jason Krs Jun 05 '16 at 14:21
1

The problem is that your global variable my_data and the argument variable of your success function are not the same variable. You can change the argument name then assign its value to your global variable.

success: function (result){ my_data = result; }

Check this fiddle to clarify this.

Update: You also have the problem answered by @Poiz

Nico
  • 858
  • 10
  • 20
  • nope. Just did that. Still the same. my_data is still undefined. `success: function (result){ my_data = result; console.log(my_data); } }); alert(my_data);` – Jason Krs Jun 05 '16 at 13:23
  • 1
    Yes, its true you have two problems. This one and the encoding problem answered by @Poiz – Nico Jun 05 '16 at 13:35