views:

47

answers:

3

I'm trying to retrieve data from a php file named return that just contains

<?php
echo 'here is a string';
?> 

I'm doing this through an html file containing

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
  <script> 
  var x;
  $.get("return.php", function(data){
   x = data;
 }) 
 function showAlert() {alert(x);}

  $(document).ready(function(){
   alert(x);
 });
  </script>
</head>
<body>
  <input type = "button" value = "Click here" onClick="showAlert();">
</body>

</html>

When the button is clicked it retrieves and displays the code fine, but on the $(document).ready thing, it displays "undefined" instead of the data in return.php. Any solutions?

Thanks.

+3  A: 

the document.ready is running before the $.get has returned the msg probably

var x;
function showAlert() {alert(x);}

$(document).ready(function(){
   $.get("return.php", function(data){
      x = data;
      showAlert();
   }) 
});

that should work fine

SinneR
+1, I was just writing the same answer:)
Alastair Pitts
+2  A: 

The ajax probably has not loaded yet.

 var x;

 function showAlert() {alert(x);}

  $(document).ready(function(){
   $.get("return.php", function(data){
    x = data;
    alert(x);
  }); 
 });
Moak
+2  A: 

It isn't a question of scope, it's a question of order of events. $.get is an asynchronous call, so it may not finish yet by the time your page loads in the browser (it's a fairly small page so I imagine it loads quite quickly).

R0MANARMY