i want to pass a javascript string to php … WHICH is RIGHT after the code .. in the script.
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
this does not work.
What should i do ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When someone visits a website, this is generally what happens:
So PHP and JavaScript are basically at different ends of the process. Only the server handles PHP, and only the client handles JavaScript.
To “give” a string to PHP, you’d have to make a request of the PHP page, sending that string as a GET variable:
There are a few ways to do this with JavaScript.
If you only care about making that request on the PHP page, and you don’t need to worry about receiving any information back, you can just create an image and use the URL as the source:
Even though you’re requesting an image, the server doesn’t know that, and will process your request by calling the PHP evaluating it, etc.
You can make an actual AJAX request. Start by creating an XMLHttpRequest object:
There are some issues in IE with cached responses on AJAX requests, so make the url unique:
Tell your XHR where you want it to go, and how you want it to get there:
Set up a method that will check for when a response is received:
And finally, send the request:
Some notes to keep in mind:
successfunction yourself, to handle the string that your PHP page will return.xhr.responseXMLif you want, but that’s usually just a hassle for me.onreadystatechangethe way I have will (I believe) introduce memory leaks in some versions of IE