K
K
kickass772021-07-30 06:41:34
AJAX
kickass77, 2021-07-30 06:41:34

How to pass value from ajax to another page?

Hello.
Please let me know how this is done correctly.

I am getting a value on one page and want to pass that value to another page.

<script>
  $(document).ready(function(){  
    $("#click_btn" ).click(function(){

      var num = 12345;

      console.log(num);

      $.ajax({  
        url: "test.php",  
        cache: false,  
        data: ({type:"getnum", num:num}),
        success: function(html){  
          setTimeout(function(){ document.location.href = "site.ru/test.php"; }, 2000);
        }  			
      }); 
      return false;
    });
  });  
</script>


In test.php file:

<?php
  
 
  if($_GET['type'] == 'getnum') {
    $num = $_GET['num'];

     echo $num;
  }


  ?>


And below I have the html code from the test.php page where I want to work with $num
Most likely, the value is passed in this way, but due to the fact that I have to go to this page, the values ​​\u200b\u200bare reset.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Samuello, 2021-07-30
@Samuello

If this is some simple data, like name, phone number, etc., then use query parameters:

success:  function(response){  
    setTimeout(function() {
        document.location.href = `site.ru/test.php?number=${response.number}&name=${response.name}`;
     },  2000);
}

And if it is already more complex in its logic and large in volume data, then use local storage:
success:  function(response){
    localStorage.setItem('some_key', JSON.stringify(response.data));

    setTimeout(function() {
        document.location.href = 'site.ru/test.php';
     },  2000);
}

and accordingly get this data on another page:
let helloHabr = JSON.parse(localStorage.getItem('some_key'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question