Xahed Kamal Xahed Kamal - 7 months ago 24
Javascript Question

Send a variable to a PHP page and open the page in new tab

I've this code

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

$.ajax({
type: "POST",
url: "preview.php",
data: "my_data=" + my_data,
success: function() {
window.open('preview.php');
},
});
});


Above codes open the
preview.php
but I'm getting this error -


Notice: Undefined index: my_data in
C:\xampp\htdocs\tb-builder\preview.php on line 3


This is what I've in
preview.php
-

<?php
$data= $_POST['my_data'];
echo $data;
?>


Can anybody help me to solve this please? Thanks

Answer

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>