开发者

Submit form using Javascript with added variable

开发者 https://www.devze.com 2023-03-29 04:40 出处:网络
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 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&quo开发者_JAVA技巧t; 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
    }
?>


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>


<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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号