Skip to content

Instantly share code, notes, and snippets.

@greg-randall
Created July 18, 2023 13:24
Show Gist options
  • Select an option

  • Save greg-randall/0fedddddbb0978a57604ad7c14d3794e to your computer and use it in GitHub Desktop.

Select an option

Save greg-randall/0fedddddbb0978a57604ad7c14d3794e to your computer and use it in GitHub Desktop.
I needed to send a form's data to two different locations, we couldn't edit the site, but could have them add javascript. The script scrapes out the current form action and adds a field for the page's URL. When the form is submitted, we send the data to the second submit location (set on line #22), then remove the page url field (since we don't …
var form = document.getElementById("form-id"); //get the form for modifications we need to make
//get the form action and then remove the form action so we can control when the form is sent
var action = form.action;
form.action = "";
console.log(`action: ${action}`);
//create a hidden field for getting the page url,
//since in php the HTTP_REFERER/HTTP_ORIGIN in PHP only returns domain
var hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = "current_page_url";
hiddenInput.value = window.location.href;
form.appendChild(hiddenInput); //add the field fo the form
form.addEventListener("submit", function(event) { //listen for form submit click
event.preventDefault(); //pevent the default action so we can control the form
//going to do an ajax style push of the form to a secondary location
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://example.com/input.php", true);
//make sure to add a header to the form that you're submitting to cross-domain
//header("Access-Control-Allow-Origin: *");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(formData);
console.log('submitted to external');
//removing our hidden url field, so we don't send our extra field
var elementsToRemove = form.querySelectorAll('input[name="current_page_url"]');
elementsToRemove.forEach(function(element) {
element.parentNode.removeChild(element);
});
console.log('extra feild removed');
//now going to do the normal submit
form.action = action;
form.submit(); //submit the form
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment