[TIPS&TRICKS] Passare una variabile da JavaScript a PHP, e viceversa

Da PHP a JavaScript

<script>
  var var_js = <?php echo json_encode($var_php); ?>;
</script>

Da JavaScript a PHP

// JavaScript
<script>
  window.open('pagina.php?var_js1='+var_js1+'&var_js2='+var_js2);
</script>

// pagina.php
$var_php1 = $_GET['var_js1'];
$var_php2 = $_GET['var_js2'];

Da JavaScript a PHP e ritorno

// JavaScript (jQuery) e Ajax
<script>
  $.ajax({
   type: "GET",
   url: "pagina.php",
   data: "var_js1=" + var_js1+ "var_js2=" + var_js2,
   error: function(){
     alert("errore");
   },  
   success: function(result){
     alert(result);
   }
 });
</script>

// pagina.php
$var_php1 = $_GET['var_js1'];
$var_php2 = $_GET['var_js2'];
echo json_encode($risposta_php);
tips&tricks

Related Articles

0 Comment

Rispondi