3

I have the following form:

HTML

<form id="myForm" action="" method="post">
<div id="edit-box">
<INPUT type="submit" name="save-text" id="save-text" value="Save">
<textarea id="editor" name="editor">
<?php echo $content; ?>
</textarea>
</div>
</form>

PHP

if ($_POST["save-text"]){
    // get form data and do stuff here
}

How can I make sure that the PHP script is run only when the submit button is clicked and no other time?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mumbo Jumbo
  • 360
  • 1
  • 2
  • 12
  • 1
    Anything wrong with your current code? – zerkms Jul 31 '12 at 03:01
  • yep..it doesn't do anything. I want to trigger the php based on the button id inside the form. can you please tell me how can I do that? – Mumbo Jumbo Jul 31 '12 at 03:02
  • Just fill in the `action` with your php path and done. `action="path/filename.php"` – elclanrs Jul 31 '12 at 03:03
  • 1
    Probably want to make use of `isset()` when you check if the form has been submitted `if (isset($_POST['save-text'])) {`. Also try debugging it by throwing in an `echo 'submitted';` inside your if statement to check that it's being submitted. – Jeemusu Jul 31 '12 at 03:09
  • @user21472 What worked for you? filling in the `action` or using the `isset()` ? Let us know so one of us can write it in as an answer for you to accept. – Jeemusu Jul 31 '12 at 03:13
  • sorry....here's what worked for me: if(isset($_POST['save-text'])){ – Mumbo Jumbo Jul 31 '12 at 03:19

2 Answers2

2

Add this before the HTML tag at the start of the page.
Also don't forget to change the page name extension from .html to .php

if (isset($_POST['save-text'])) {
    // get form data and do stuff here
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rasim Fryal
  • 41
  • 1
  • 2
  • 7
1

The problem is that if($_POST["save-text"]) returns false and so your code isn't being executed. You will need to wrap the $_POST["save-text"] with the isset() function. isset() can be used to check the existence of a certain variable and returns TRUE if a variable exists and has a value other than NULL or FALSE.

The correct code would look like this:

if (isset($_POST['save-text'])) {
    //Do something
}

You should also make sure your submit buttons have a 'value' attribute. If they don't, there wont be a value in the $_POST array and so isset($_POST["submit"]) would return false.

Example:

<input type="submit" name="submit">

isset($_POST["submit"])   // returns false

<input type="submit" name="submit" value="submit">

isset($_POST["submit"])   // returns true.
Jeemusu
  • 10,415
  • 3
  • 42
  • 64