JDelage
JDelage

Reputation: 13672

Not understanding why $_POST isn't set after click on input button

In the context of a form without a submit button, I am not understanding why the $_POST variable doesn't get set. Here is my code:

<?php
  $view="blablabla";
?>
<form class="" method='POST' accept-charset="UTF-8" action='index.php'>
<p>
  <textarea rows="4" cols="60" name='article' id='article' WRAP=SOFT>
    <?php
      echo $view;
    ?>
  </textarea>
</p>    
<p>
  <input type="button" name='do1' id='do1' value="do 1"/>
  <input type="button" name='do2' id='do2' value="do 2"/>
</p>
</form>

<?php
  var_dump("POST :",$_POST);
?>

Shouldn't the var_dump show a value to $_POST once I click one of the 2 buttons?

Upvotes: 0

Views: 1661

Answers (1)

purpletree
purpletree

Reputation: 1943

Nope- the input types have to be submit (<input type="submit"/>) for the form to be submitted. A POST request has to be sent to your PHP script in order for there to be any values populated in the $_POST array :)

EDIT: They don't have to be submit, but in the case of the code above, with no external triggers on the buttons, you'll need submit buttons :)

For your multiple buttons issue:

If you're using JavaScript/Ajax to send the POST request to PHP on the button click, you'll need to do something similar:

if (isset($_POST['x'])) {
    var_dump($_POST);
    exit;
}

This is so the script doesn't return the HTML of the page (i.e. your form)- this isn't an issue if you're POSTing to another page :)

Below is some sample jQuery code to send some POST data on button click (not going to give you the exact code, you'll have to modify it to your needs!)

$('#my_button').click(function(){
    $.post('myfile.php', data, function(response) { //the var 'data' is the POST data you're sending
        // handle response here, the data being in the response variable 
    });
});

Upvotes: 7

Related Questions