I want to pass a javascript string to php ... WHICH RIGHT after the code .. in a script.
<script type="text/javascript"> var myvar = "mytext" ; <?php echo myvar ; ?> </script>
this does not work. What should I do?
When someone visits a website, this usually happens:
, PHP JavaScript . PHP, JavaScript.
"" PHP, PHP, GET:
http://www.yourdomain.com/some_php_page.php?myvar=mytext
JavaScript.
PHP, - , URL- :
var fakeImg = new Image(); fakeImg.src = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext';
, , PHP, ..
AJAX. XMLHttpRequest:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
IE AJAX, URL :
var url = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext&unique=whatever';
XHR, , , :
xhr.open('GET', url, true); // The "true" parameter tells it that we want this to be asynchronous
, , :
xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status < 400) { success(xhr.responseText); } };
xhr.send(null); // We set "null" because some browsers are pissy
, :
success
xhr.responseXML
onreadystatechange
PHP , javascript - , , PHP , javascript.
AJAX.
. , php-, , . , , , . , , (php), - xmlhttprequest javascript ( ajax).
, ... php javascript. , script , .
, , , , .
:
<script type="text/javascript"> <?php $myvar = "mytext"; ?> var myvar = "<?php echo $myvar; ?>" ; </script>
It then sets the JavaScript myvarvalue to PHP $myvar, so both of them remain unchanged. If you are trying to do something else, you need to expand your example.
myvar
$myvar