0

How do I execute PHP using a JavaScript onclick button? I can get the form to submit, but the PHP does not get executed. I assume it's because if(isset($_POST['form']))

Here is the PHP I want to execute:

if(isset($_POST['form']))
{
    if(!isset($error))
    {
        $database->query('UPDATE table SET field = :value WHERE id = :id', array(':field' => $value, ':id' => $id));
    }
}

Here is my button that is BEFORE my <form> tag:

<div onclick="javascript: $(\'#form\').submit();">Update</div>

And of course my <form> tag looks something like this:

<form name="form" id="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <select name="value">
    <option value="1">Value1</option>
    <option value="2">Value2</option>
    <option value="3">Value3</option>
  </select>
</form>
2
  • I can get the form to submit, but the PHP does not get executed. I assume it's because if(isset($_POST['form'])) Commented Aug 2, 2012 at 2:01
  • I can't use the name=form in the <form> tag? Commented Aug 2, 2012 at 2:08

2 Answers 2

1

PHP generally runs server side. JavaScript generally runs in the browser. You need to put the PHP in the file blah.php on the server.

Sign up to request clarification or add additional context in comments.

3 Comments

I can get the form to submit, but the PHP does not get executed. I assume it's because if(isset($_POST['form']))
Change $_POST['form'] to $_POST['foo'] where foo is the name attribute of the input element you care about.
Ah, of course. How stupid of me. Since I might have more than one input field in the form I was hoping to use the name=form in the <form> tag. But your suggestion will work.
0

I doubt you have a $_POST['form'] variable. $_POST will contain all of your form element's id's like email, phone, name, etc... $_POST['email'], but would likely not contain a general 'form' key.

I would use if (isset($_POST))

1 Comment

I thought about using that but I have two forms on the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.