Passing Javascript String in PHP

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?

+3
source share
4 answers

When someone visits a website, this usually happens:

  • Their browser sends a request to the server.
  • The server is evaluating this request.
  • The server understands that "Egad, the page they are requesting to has PHP!"
  • The server evaluates PHP and sends the results to the browser.
  • The browser parses the content that it receives.
  • The browser understands: "Egad, the page I got has JavaScript!"
  • The browser evaluates JavaScript completely on the client machine.

, 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 , , PHP.
    • xhr.responseXML, , .
    • onreadystatechange, ( ), IE
+11

PHP , javascript - , , PHP , javascript.

AJAX.

+5

. , php-, , ​​ . , , , . , , (php), - xmlhttprequest javascript ( ajax).

, ... php javascript. , script , .

, , , , .

0

:

<script type="text/javascript">
  var myvar = "mytext" ;

 <?php echo myvar ; ?>
</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.

-1
source

All Articles