2

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"></script>
  <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 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.