开发者

How do I assign a javascript variable to a PHP variable?

I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:

<script type="text/javascript">
function redirectToFacebook()
{
    var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script&g开发者_如何学Got;

<?php
    $_SESSION['sess_facebook_message'] = facebookMessage;
?>

Any help is really appriciable.

Thanks in advance


Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.

However...

If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.

For example...

JavaScript:

function something() {
    // do something with somevar
    somevar = 'content';
    // make an AJAX request to setvar.php?value=content
}

PHP:

$_SESSION['somevar'] = $_GET['somevar'];

Make sure you take security issues of client-generated data into account, though.


If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:

1) Load a new page with Javascript parameters encoded either as POST or GET 2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET

A simple example using a GET request (you simply append your parameters to the URL):

<script>
    window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>

You probably want to assign this piece of code to a button or something...


what you are trying to achieve is not possible due to API limitation.It does not provide that.


may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.

may be, im realy not shure try this.

<?php
function redirectToFacebook() { 

var facebookMessage = ?>
<script>
    document.write(encodeURI(document.getElementById('txt_msg').value)); 
</script>
<?php
}
?>

or using cookies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜