一键提交两份表格

发布于 2024-12-11 06:22:09 字数 147 浏览 0 评论 0原文

我有两种 HTML 表单,一种使用 PHP 在输入数据库时​​提交数据,另一种将用户定向到 paypal 付款页面,我的问题是用户必须提交这两种表单,这当然是我不希望他们这样做的必须做的。有没有办法对两种表单使用一个提交按钮?

(欢迎使用 JavaScript)

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?

(Javascript is welcome)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

清醇 2024-12-18 06:22:09

表单提交会导致页面导航到表单的操作。因此,您不能以传统方式提交这两种表格。如果您尝试通过在每个表单上连续调用 form.submit() 来使用 JavaScript 来执行此操作,则除最后一次提交之外的每个请求都将被中止。因此,您需要通过 JavaScript 异步提交第一个表单:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(encodeURIComponent(f.elements[i].name) + "=" +
        encodeURIComponent(f.elements[i].value));
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

document.forms.payPal.submit();

2023 update

原始答案仍然工作得很好,但这里有一个使用 fetch() 和现代语法的更新:

function submitBothForms() {
    const { updateDB, payPal } = document.forms;
    fetch(updateDB.action, {
        method: updateDB.method,
        headers: { "content-type": updateDB.enctype },
        body: new FormData(updateDB),
    });

    payPal.submit();
}

请注意,虽然通常您会 < code>await 对 fetch 的调用,我们在这里不这样做,因为,既然你想同时提交两个表单,你就不必关心 updateDB 表单是否被成功的。因此,延迟提交 PayPal 表格是没有意义的。

如果这不是您想要的,您可以序列化调用,并逐个提交表单,添加一些错误处理:

async function submitBothForms() {
    const { updateDB, payPal } = document.forms;
    const res = await fetch(updateDB.action, {
        method: updateDB.method,
        headers: { "content-type": updateDB.enctype },
        body: new FormData(updateDB),
    });
    if (!res.ok) {
        const err = new Error(`DB Update Failed! Status: ${res.status}`);
        const isJSON = res.headers.get("content-type") == "application/json";
        err.body = await (isJSON ? res.json() : res.text());
        throw err;
    }

    payPal.submit();
}

这样,如果第一个表单不成功,则会抛出错误,从而阻止第二个表单正在提交。我将继续处理错误并向您显示错误消息。

A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(encodeURIComponent(f.elements[i].name) + "=" +
        encodeURIComponent(f.elements[i].value));
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

document.forms.payPal.submit();

2023 update

The original answer still works perfectly well, but here's an update using fetch() and modern syntax:

function submitBothForms() {
    const { updateDB, payPal } = document.forms;
    fetch(updateDB.action, {
        method: updateDB.method,
        headers: { "content-type": updateDB.enctype },
        body: new FormData(updateDB),
    });

    payPal.submit();
}

Note that, while normally you would await a call to fetch, we don't do it here because, since you want to submit both forms at the same time, you must not care about whether the updateDB form was successful. So, there's no point in delaying submitting the payPal form.

If that isn't what you want, you could serialize the calls, and submit the forms one after the other, adding in some error handling:

async function submitBothForms() {
    const { updateDB, payPal } = document.forms;
    const res = await fetch(updateDB.action, {
        method: updateDB.method,
        headers: { "content-type": updateDB.enctype },
        body: new FormData(updateDB),
    });
    if (!res.ok) {
        const err = new Error(`DB Update Failed! Status: ${res.status}`);
        const isJSON = res.headers.get("content-type") == "application/json";
        err.body = await (isJSON ? res.json() : res.text());
        throw err;
    }

    payPal.submit();
}

This way, if the first form is unsuccessful, an error is thrown, preventing the second form from being submitted. I'll leave handling the error and displaying error messaging to you.

泪眸﹌ 2024-12-18 06:22:09

您应该能够使用 JavaScript 执行此操作:

<input type="button" value="Click Me!" onclick="submitForms()" />

如果您的表单有 ID:

submitForms = function(){
    document.getElementById("form1").submit();
    document.getElementById("form2").submit();
}

如果您的表单没有 ID 但有名称:

submitForms = function(){
    document.forms["form1"].submit();
    document.forms["form2"].submit();
}

You should be able to do this with JavaScript:

<input type="button" value="Click Me!" onclick="submitForms()" />

If your forms have IDs:

submitForms = function(){
    document.getElementById("form1").submit();
    document.getElementById("form2").submit();
}

If your forms don't have IDs but have names:

submitForms = function(){
    document.forms["form1"].submit();
    document.forms["form2"].submit();
}
与酒说心事 2024-12-18 06:22:09

您可以使用 AJAX 提交第一个表单,否则其中一个表单的提交将阻止另一个表单的提交。

You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.

层林尽染 2024-12-18 06:22:09

在 Chrome 和 IE9 中(我猜所有其他浏览器也是如此),只有后者会生成套接字连接,第一个将被丢弃。 (浏览器检测到这一点,因为两个请求都是在上面代码中的一个 JavaScript“时间片”内发送的,并丢弃除最后一个请求之外的所有请求。)

如果您有一些事件回调,则执行第二次提交(但在收到回复之前),第一个请求的套接字将被取消。这绝对没有什么值得推荐的,因为在这种情况下,服务器很可能已经处理了您的第一个请求,但您永远无法确定。

我建议您使用/生成一个可以在服务器端进行处理的请求。

In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)

If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.

I recommend you use/generate a single request which you can transact server-side.

差↓一点笑了 2024-12-18 06:22:09

当前选择的最佳答案过于模糊,不可靠。

在我看来,这是一种相当安全的方法:

(Javascript:使用 jQuery 来编写更简单)

$('#form1').submit(doubleSubmit);

function doubleSubmit(e1) {
    e1.preventDefault();
    e1.stopPropagation();
    var post_form1 = $.post($(this).action, $(this).serialize());

    post_form1.done(function(result) {
            // would be nice to show some feedback about the first result here
            $('#form2').submit();
        });
};

发布第一个表单而不更改页面,等待该过程完成。然后发布第二个表格。
第二篇文章将更改页面,但您可能也希望为第二个表单提供一些类似的代码,获取第二个延迟对象(post_form2?)。

不过,我没有测试代码。

The currently chosen best answer is too fuzzy to be reliable.

This feels to me like a fairly safe way to do it:

(Javascript: using jQuery to write it simpler)

$('#form1').submit(doubleSubmit);

function doubleSubmit(e1) {
    e1.preventDefault();
    e1.stopPropagation();
    var post_form1 = $.post($(this).action, $(this).serialize());

    post_form1.done(function(result) {
            // would be nice to show some feedback about the first result here
            $('#form2').submit();
        });
};

Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).

I didn't test the code, though.

归属感 2024-12-18 06:22:09

如果你想用一个按钮提交两个表单,你需要这样做:

1- 使用 setTimeout()

2- 允许显示弹出窗口

<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);   
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);   
}
</script>
<form  target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>

javascript 不会同时提交两个表单。我们使用一个按钮不是同时提交两个表单,而是在几秒后提交。

编辑:当我们使用此代码时,浏览器不允许弹出。
如果您像我一样在软件中使用此代码,只需将浏览器设置为显示弹出窗口,但如果您在设计网站时使用它,则浏览器是一个障碍,代码无法运行。

if you want to submit two forms with one button you need to do this:

1- use setTimeout()

2- allow show pop up

<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);   
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);   
}
</script>
<form  target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>

javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.

edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

话少情深 2024-12-18 06:22:09

如果您有一个常规的提交按钮,您可以向其添加一个 onclick 事件来执行以下操作:

document.getElementById('otherForm').submit();

If you have a regular submit button, you could add an onclick event to it that does the follow:

document.getElementById('otherForm').submit();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文