Jump to content

What is the simplest way to display an alert with a the value of a php variable


jayhawker

Recommended Posts

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.

Link to comment
Share on other sites

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;?>" />

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.