0

I need to pass a value from PHP back to my javascript. I have tried so many things but can't get it to work. Here is my code.

<script type="text/javascript">     
    life = {};
    life.anjaxEnter = function(finished) {
        $.ajax({
        dataType:"json",
        type:"POST",
        data:mydata,
        url:"myurl.php",
        async:false,
        success:life.receiveResult,
        });
        setTimeout("location.href='myredirectionurl'", 1000); // Redirect after 1 second
    }
    life.receiveResult = function(result) {
        alert(result);
    }   
</script>

I need to pass a specific value from the PHP file back to life.receiveResult and then add this to the redirection url.

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
sethcarlton
  • 71
  • 1
  • 6
  • possible duplicate of [how to pass these strings from php to javascript](http://stackoverflow.com/questions/3174092/how-to-pass-these-strings-from-php-to-javascript) and http://stackoverflow.com/questions/8626183/passing-values-from-php-to-javascript?rq=1 – Anthony Hatzopoulos Jun 05 '13 at 19:30
  • 2
    you have an extra comma after susccess – stackErr Jun 05 '13 at 19:30
  • Can you search before posting questions. I’ve seen this question answered dozens of times on Stack Overflow. – Martin Bean Jun 05 '13 at 19:35
  • Thanks for the help. I had seen answers as well, however, they did not seem to work for me. Got it working now though! – sethcarlton Jun 06 '13 at 22:06

2 Answers2

2

The biggest problem is probably that at the time when you assign life.receiveResult to success, life.receiveResult is undefined. You need to define it before you assign it to something else.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

myurl.php needs to return a JSON result when it's called. Something like this:

<?php
header("Content-Type: text/json");
$mydata = "Hello";
echo json_encode(array('ok' => true, 'mydata' => $mydata));
?>

Have a look at the json_encode docs, the header docs and some of the other answers for more information.

Community
  • 1
  • 1
Duncan Lock
  • 12,351
  • 5
  • 40
  • 47