1

I have the following button which opens a new tab/window and redirecting to test.php page. I wanted to post the data of $a to test.php
<input type="button" onclick="window.open('test.php?var=<?php echo $a;?>','_blank');" value="test"/>
test.php
$b = $_GET['var'];

$_GET in the above case will be able to retrieve the data posted from the url query, however if I change it to $b = $_POST['var']; I get undefined index error for var.

I read from other posts that I should not use GET for submission of sensitive data. So my question is: How can I modify the code such that I can post the data of variable var to test.php using $_POST?

Community
  • 1
  • 1
DunnoHowToCode
  • 491
  • 1
  • 4
  • 13

3 Answers3

1

GET requests include parameters in the URL. If you have a page 'foo.com/bar.php' you can pass it GET parameters in the URL, 'foo.com/bar.php?var=myvar'.

You can then retrieve the parameter using $_GET:

$var = $_GET['var'];

In a POST request, parameters are included in the request body, not in the URL. So if you want to send var using POST you need to use AJAX or submit a form with method="POST".

In your case you're using GET and trying to get the value from $_POST. That's not possible

dimlucas
  • 4,574
  • 5
  • 35
  • 48
  • Hmm, I guess I understood what you meant. So there is no way that I can pass the data of `var` with just ``(a simple button) alone? The reason why I didn't use
    is because I could not aligned the button for the form horizontally to the other simple buttons like . It automatically generates a new line which I could not get rid.
    – DunnoHowToCode Jun 24 '16 at 09:54
  • @DunnoHowToCode No you can't :/ Not without a form or AJAX – dimlucas Jun 24 '16 at 09:55
0

With $_GET you will pass the variables via the URL.

If you want to use $_POST, you have to use AJAX:

<input type="button" class="post" value="test"/>


 <script type="text/javascript">
            jQuery(document).ready(function($){
                $(".post").on("click",function(){
                    $.ajax({
                        url: "test.php",
                        type: "POST",
                        success: function(response){
                              //do action  
                        },
                        error: function(){
                              // do action
                        }
                    });
                });
            });
        </script>
pguetschow
  • 4,086
  • 5
  • 26
  • 39
0

I think if you want to do like that you should create hidden value and then when you click on your button then submit that form as a post request to test.php

Don't forget to add target="_blank" to your form for open in new tab

and if you don't want to create form in this page you can redirect it to new page and use javascript for submit form in new page for send post request to test.php

Wiriya Rungruang
  • 188
  • 1
  • 1
  • 8