0

I have an HTML form that submits to a PHP script through two different links that fire JavaScript code. What I need is to be able to submit the form differently through the two JavaScript links so that I can check for that difference on the PHP side. I realize I could do this with submit buttons, but I'm trying to avoid that. I was hoping something like this would work:

foo.html

<form name="fooform" action="fooscript.php" method="POST">
    <input type="text" name="footext">
</form>

<a onclick='document.fooform.submit();' href='#'>Do something</a>
<a onclick='document.fooform.submit();' href='#'>Do something else</a>
<!--
<a onclick='document.fooform.submit(0);' href='#'>Do something</a>
<a onclick='document.fooform.submit(1);' href='#'>Do something else</a>
-->

fooscript.php

<?php
    if(submit(0)){
        //Do something
    }
    if(submit(1)){
        //Do something else
    }
?>

2 Answers 2

1

I would create a hidden field in the form.

<input type="hidden" id="submit_action" name="submit_action" value="" />

extract the details of the submitting the form in a script tag

function submitWithCommand(commandValue) {
    if (e = document.getElementById("submit_action")) e.value = commandValue;
    document.fooform.submit();
    return false;
}

then add the value before submitting the form.

<a onclick='submitWithCommand("something");' href='#'>Do something</a>
<a onclick='submitWithCommand("something else");' href='#'>Do something else</a>
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for encapsulating this into a function rather than adding more crap in the onClick.
Worked great, and the encapsulation makes it simple to duplicate. Thanks!
1
<form name="fooform" action="fooscript.php" method="POST">
    <input type="text" name="footext" />
    <input type="hidden" name="triggered_by" value="" />
</form>

<a onclick='document.triggered_by.value=1; document.fooform.submit();' href='#'>Do something</a>
<a onclick='document.triggered_by.value=2; document.fooform.submit();' href='#'>Do something else</a>

PHP:

var_dump($_POST['triggered_by']); // 1 or 2

1 Comment

For some reason, this method was not submitting the form. Thanks for your help!

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.