"send a variable to a php page and open the page in new tab" Code Answer

5

main error is , window.open('preview.php'); loads the page preview.php ,
you are not sending any data with post/get request while loading it using window.open('preview.php'); and you are expecting value at $_post['my_data']

  $(document).on('click', '#button', function(){
    var my_data = 'test test tes';

    $.ajax({
      type: "post",
      url: "preview.php",
      data: "my_data=" + my_data,
    });
  });

preview.php

<?php
    if(isset($_post['my_data']){
    $data= $_post['my_data'];
    header('location:preview.php?my_data=$data');  //reload preview.php with the `my_data`
   }
   if(isset($_get['my_data'])){
      $data=$_get['my_data'];    
    echo $data;             //display `my_data` as you requested
   }
?>

update

with out using ajax ,to achieve what you required.

$(document).on('click', '#button', function(){
    var my_data = 'test test tes';
        window.open('preview.php?my_data='+my_data);
  });

preview.php

<?php 
 if(isset($_get['my_data'])){
        $data=$_get['my_data'];    
        echo $data;          
 }
?>


final update


actually you don't need ajax at all , because you are going to another page with the data .


to avoid get request

wrap the button inside a form with hidden input having value my_data and set action="preview.php" like below

<form action="preview.php" method="post">
  <input type="hidden" id="my_data" value="test test tes">
  <button type="submit" id="button">post</button>
</form>
By Harminder on May 28 2022

Answers related to “send a variable to a php page and open the page in new tab”

Only authorized users can answer the Search term. Please sign in first, or register a free account.