3

I read this post and assumed the technique in the answer would work with ajax calls. I have my ajax and php code below but it does not work.The client does not recognize the 'passed' variable. I do not know why nor how to remedy this.

Javascript

var irrelevant = 'irrelevant';

   $('body').click(function(){


            $.ajax({
            type: 'POST',
            url: 'test.php',
            data: {mydata: irrelevant},    
            success: function(){

            console.log('worky');

            alert(myvar); // NOT worky!

                    }

            });

    });

PHP File

<?php


$thing = 10;


?>


<script>

var myvar = "<?php echo $thing; ?>";

</script>
2
  • 1
    there is no accepted answer in the question you mention. Commented Oct 28, 2013 at 10:28
  • Sorry I was reading the comments and didn't look for the green check Commented Oct 28, 2013 at 10:29

2 Answers 2

4

try this in your ajax.success

success: function(data){
   console.log('worky');
   alert(data); // It should now, worky!
}

and in you php

<?php

   echo 10;

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

1 Comment

works great, although it would be nice to have an example or an array of variables instead of a single variable ;-)
0

try this in php

<?php  $thing = 10; ?>


<script>

var myvar = "<?php echo $thing; ?>";

</script>

javascript

$('body').click(function(){

            $.ajax({
            type: 'POST',
            url: 'test.php',
            data: {mydata: irrelevant},    
            success: function(data){
                $("#hiddendiv").html(data);
                alert(myvar);
            }
       });  
});

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.