DunnoHowToCode
DunnoHowToCode

Reputation: 541

$_GET is working but not for $_POST for url query

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?

Upvotes: 1

Views: 70

Answers (3)

Wiriya Rungruang
Wiriya Rungruang

Reputation: 318

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

Upvotes: 0

pguetschow
pguetschow

Reputation: 5337

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>

Upvotes: 0

dimlucas
dimlucas

Reputation: 5141

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

Upvotes: 1

Related Questions