How to pass variable value from javascript to php? [duplicate]

1

How can I pass a php variable to the value of a select, whenever a different option is selected.

I have tried as below but it returns me [object HTMLSelectElement]

$("select#tipo_documento").change(function (event) {

            var tipo_documento = document.getElementById('tipo_documento').value;
})

<?php
                $tipo_documento = "<script>"

         . "document.write(tipo_documento)"

         . "</script>";
            ?>
    
asked by anonymous 23.08.2016 / 14:57

3 answers

3

You are mixing FRONTEND (JavaScript) codes with BACKEND (PHP) codes.

You can pass the value of the JavaScript variable tipo_documento via Ajax to a PHP file.

$("select#tipo_documento").change(function (event) {
      var tipo_documento = document.getElementById('tipo_documento').value;
      var req = this.createXMLHTTPObject();
      if (!req) return;
      var url = 'http://www.seu_site.com.br/seu_php.php?tipo_documento = ' . tipo_documento;
      req.open('GET',url,true);
      req.onreadystatechange = function () {          
        if (req.readyState != 4) {
            return;
        }
        if (req.status != 200 && req.status != 304) {
            alert('HTTP error ' + req.status);
            return;
        }


        alert('ok');
    }
    if (req.readyState == 4) return;
    req.send();


});
    
23.08.2016 / 15:01
1

I have also come across this doubt and after a long time thinking I found an extremely simple solution to pass a variable from js or HTML to PHP .

I basically created a form that when the input (type="submit") would send a variable from html / js to php ... that can be used on the page itself or even on another page page. another method can also be used ... you can set a cookie in php's name to your choice to be sent ... in case you would use the code:

setcookie('nome do cookie', '<script>document.write(varivel);</script>' , time()+(30*24*3600));
    
01.11.2016 / 21:36
-2

Use a text element hide with unique id. Or open and close the PHP tag with echo in the value. But you have to take into account the order of HTML creation in the browser.

    
23.08.2016 / 15:06