How to pass javascript variable value to php?

Asked

Viewed 17,426 times

1

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

I tried as below, but 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>";
            ?>
  • There are over a hundred questions about this on the site, the suggestion is to search to see which one is more like what you want: http://answall.com/search?q=vari%C3%A1vel+javascript+php

3 answers

3

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

It is possible to pass the value of the Javascript variable tipo_documento via Ajax to an archive PHP.

$("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();


});

1

I have been through this doubt and after a long time thinking I found an extremely simple solution of pass a js or HTML variable to PHP.

I basically created a form that when the input (type="Submit") would send an html/js variable to php ... that can be used on the page itself or even on another page. another method can also be used... you can set a cookie in php of name 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));

-2

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.