jayhawker Posted April 1, 2011 Share Posted April 1, 2011 Using Javascript, how do I do an alert and show the value of a variable? thanks Quote Link to comment https://forums.phpfreaks.com/topic/232369-what-is-the-simplest-way-to-display-an-alert-with-a-the-value-of-a-php-variable/ Share on other sites More sharing options...
linus72982 Posted April 1, 2011 Share Posted April 1, 2011 There really isn't a way to do this as PHP is run on the server and has stopped interpreting by the time javascript takes over on the browser. You CAN pass a PHP variable to a webpage and use it via javascript with AJAX, but it would have to be it's own separate AJAX call just to grab one variable at a time - would be a bunch of overhead just to do this. I'm sure there might be a way to inject the variable into the GET variables in the address and pull them from javascript but that is beyond my slim knowledge of javascript. Quote Link to comment https://forums.phpfreaks.com/topic/232369-what-is-the-simplest-way-to-display-an-alert-with-a-the-value-of-a-php-variable/#findComment-1195382 Share on other sites More sharing options...
acefirefighter Posted April 2, 2011 Share Posted April 2, 2011 Something like one of these should work for you. They will alert as soon as the page loads. If you didn't want the $php_value in an input tag for validation reasons you could always place it in a div with display:hidden;. This isn't strictly "javascript" since you can see I loaded jQuery I am using the syntax for that. I like the second option a lot more than the first just because I am not having to send the JS to the view with a variable. <?php // Option One $php_value = 'username'; $script = <<<EOT <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { alert('$php_value'); }); </script> EOT; ?> <html> <head> <?php echo $script; ?> </head> <body> </body </html> <?php // Option Two $php_value = 'username'; ?> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var alert_value = $("#username").attr('name'); alert(alert_value); }); </script> </head> <body> <input type="hidden" id="username" name="<?php echo $php_value;?>" /> Quote Link to comment https://forums.phpfreaks.com/topic/232369-what-is-the-simplest-way-to-display-an-alert-with-a-the-value-of-a-php-variable/#findComment-1195776 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.