One form, One submission button, but TWO actions
You're running into a classic client-side limitation: a single <form> element can only have one action URL and submit to exactly one destination at a time. When you try to call two functions on the same button click and manually change document.referralForm.action before calling submit(), you end up submitting twice in quick succession, or submitting only the second action depending on browser implementation details. That's why your current pattern doesn't work reliably.
The core issue is that once form.submit() is called, the browser starts the HTTP request immediately. Changing the action attribute after calling submit() has no effect on the in-flight request, and if you call it twice, the second call may fire before the first one completes or may be ignored depending on timing. You cannot "branch" a single native form submission to two different endpoints from one button without changing how the submission happens.
There are three realistic approaches that keep your UX intact (one submit button, one success page) while satisfying both requirements: local processing + external API.
Separate concerns with parallel requests
The cleanest pattern is to handle the "local" work (validation, DB insert, emails) server-side on a single endpoint, then make a separate request to Salesforce from that same handler if needed. This keeps the HTTP flow simple and avoids race conditions.
Flow:
- User clicks the single submit button.
raf-submitted.phpreceives the POST, validates input, saves to DB, sends emails.- After those tasks complete (or asynchronously),
raf-submitted.phpcalls the Salesforce API with the same data and redirects to the success page once everything is done.
Example in PHP:
<?php
// raf-submitted.php
$target = 'raf-submitted.php'; // redirect after full completion
function handleSubmission() {
$data = ['name' => $_POST['name'] ?? '', /* etc */];
// Validate and save to DB
if (!validateAndSave($data)) {
return ['success' => false, 'message' => 'Failed to save record.'];
}
// Send emails
if (!sendEmails($data)) {
return ['success' => false, 'message' => 'Record saved, but email send failed.'];
}
// Call Salesforce API
$sfResult = callSalesforceApi($data);
if ($sfResult['ok']) {
return ['success' => true, 'message' => 'All operations completed successfully.'];
} else {
// Decide whether to fail the whole transaction or log as warning.
return ['success' => false, 'message' => 'Record saved and emails sent, but Salesforce integration failed.'];
}
}
$result = handleSubmission();
if ($result['success']) {
header('Location: raf-submitted.php?status=ok');
exit;
} else {
// Re-render with error message or show a partial success page
include 'raf-submitted.php'; // template that shows $result['message']
exit;
}
function callSalesforceApi(array $payload) {
// Example using cURL to https://someAddress.salesforce.com/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://someAddress.salesforce.com/api/v3/leads');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
// Add auth headers as required by your Salesforce setup
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer YOUR_ACCESS_TOKEN',
'Content-Type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
return ['ok' => true];
} else {
return ['ok' => false, 'error' => $response ?: 'Unknown API error'];
}
}
The key point: the form still posts to raf-submitted.php, and that single endpoint decides whether to redirect immediately or show an error. Salesforce is called as a side effect of that same request.
If your Salesforce integration can tolerate eventual consistency (e.g., the lead must exist in your DB before syncing), you might even fire the API call asynchronously via a job queue, then redirect regardless. That improves responsiveness but introduces ordering guarantees you'll need to document.
Why changing action mid-click doesn't work
Your JavaScript attempts:
function FormSubmission() {
document.referralForm.action = "raf-submitted.php";
document.referralForm.submit();
return true;
}
function SalesForceSubmission() {
document.referralForm.action = "https://someAddress.salesforce.com/";
document.referralForm.submit();
return true;
}
When both functions run on the same click, the browser already has an action attribute (either from the HTML or set previously). Changing it after calling submit() does not affect the ongoing request. If you call submit() twice, the second call may be ignored or cause unexpected behavior because the form is considered "submitted" after the first call. Even if you try to change the action between calls, the timing of when the browser initiates the HTTP transaction means the modification is too late for the first request and irrelevant for the second.
This isn't a JavaScript bug; it's how the HTML spec and browsers implement form submission. You can intercept with submit() or use AJAX, but you still can't send two concurrent native POSTs from one button without extra pages or a different flow.
Alternative: AJAX + single redirect
If you really want to keep everything on one page and avoid any server-side orchestration of the Salesforce call, you can replace the native submission with an AJAX request to raf-submitted.php, let that endpoint handle DB/email/Salesforce in one place, and then redirect via JavaScript after it responds:
function submitForm() {
const form = document.referralForm;
const formData = new FormData(form);
fetch('raf-submitted.php', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = 'raf-submitted.php?status=ok';
} else {
// Render error message in place or redirect to an error page
alert(data.message);
}
})
.catch(err => {
console.error('Submission failed:', err);
// Fallback: show a generic error and let the user retry
});
// Prevent native submit
event.preventDefault();
}
HTML:
<form id="referralForm" name="referralForm" autocomplete="off" enctype="multipart/form-data" method="POST">
<!-- existing fields -->
<input type="submit" class="field-submit" value="Submit" onclick="submitForm()" />
</form>
This approach still uses a single logical endpoint and a single redirect, but it avoids relying on changing the action attribute. It also makes error handling more predictable because you control exactly when and how the user is redirected.
When this matters most
- Idempotency: If your Salesforce API isn't idempotent, calling it twice can create duplicate records. By funneling everything through one endpoint that decides whether to call Salesforce once, you avoid duplicates.
- Error reporting: Users expect one clear message per submission. Splitting into two separate form submissions makes it impossible to know which part failed without extra pages or complex state.
- Security and validation: All server-side validation should happen on the single endpoint that receives the POST. Don't rely on client-side checks alone; your
raf-submitted.phpis where input belongs to be trusted (or rejected).
Bottom line
You cannot reliably send a single form submission to two different URLs using one submit button and dynamic action changes. The supported pattern is:
- Keep one
<form>pointing to a single handler (raf-submitted.php). - Perform all local tasks in that handler.
- Call Salesforce from the same handler (sync or async).
- Redirect once, after everything you care about has completed or failed appropriately.
If your team prefers Laravel, this same pattern maps cleanly to controllers and queues: one POST route â controller logic â job for Salesforce if needed â redirect. The architecture remains the same; only the language changes.