pass input value to php session variable without page reload

0

Good.

What is the best way to pass an input value to a session variable in php without reloading the page?

For example, with this method the page does the reload:

<form method="post">
<input type="text" name="valor1" onchange="submit()">
</form>

<?php
session_start();

if($_POST['valor1']){
   $_SESSION['valor1'] = $_POST['valor1'];
}
?>

How can I get the same result without reload?

    
asked by anonymous 12.03.2018 / 19:43

1 answer

0

Using asynchronous loading, using Ajax.

Example with jQuery:

Form.php Page

<html>
  <body>
    <form>
      <form method="post">
        <input type="text" name="valor1" id="valor1">
      </form>
    </form>
    
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("#valor1").change( function(){
      
      $.ajax({
        type: 'POST',
        url: "salvarNaSessao.php",
        data: 'valor' + $("#valor1").val()
      }).done(function() {
        alert('dados enviados');
      });
      
    });
   </script>
  </body>
</html>

Page saveNaessess.php

<?php
session_start();

if(isset($_POST['valor1'])){
   $_SESSION['valor1'] = $_POST['valor1'];
}
?>
    
12.03.2018 / 20:48