How to pass variables from PHP to Javascript using Ajax calls

16,808

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;

?>
Share:
16,808

Related videos on Youtube

William
Author by

William

Updated on June 04, 2022

Comments

  • William
    William almost 2 years

    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>
    
    • Michał Rybak
      Michał Rybak over 10 years
      there is no accepted answer in the question you mention.
    • William
      William over 10 years
      Sorry I was reading the comments and didn't look for the green check
  • luke_mclachlan
    luke_mclachlan about 6 years
    works great, although it would be nice to have an example or an array of variables instead of a single variable ;-)