Javascript Send Form With No Target

The lines formData.append add the fields into the form dynamically.  Start by creating the form object.  Add the fields, create an xhr object, then open and send as shown in the code below.

There's one caveot ... The PHP file (the destination of the form) must have a header authorizing CORS (cross site scripting), added to the first line of the PHP file like this:
<?php
header("Access-Control-Allow-Origin: *");

The other option to enable CORS is to add this to the server's .htaccess file:
Header set Access-Control-Allow-Origin "*"
Place the above bold line in the first line of the .htaccess file.

If you don't have access to the PHP file or the .htaccess file, well ... that's the whole point.  It's a security issue.  You can't do cross site scripting unless the receiving site authorizes it.

The really great thing about the code below is that it will work from your desktop, or within an app.  It will submit data seamlessly without a callback, or in otherwords without redirecting the page.  Apps using WebView and scripts running on the desktop won't allow you to use hidden iframes as a form target, so this little trick does the job perfectly.

var formData = new FormData();
	formData.append('field1', value1);
	formData.append('field2', value2);
	formData.append('field3', value3);
	var xhr = new XMLHttpRequest();
	xhr.open('POST', 'https://www.example.com/formprocessing.php', true);
	xhr.send(formData);

Example:

javascript
See above.

Produces the result: The form is quietly sent and there's no redirect to a form landing page.

To use it put the contents of the script into a function and pass parameters into the function to fill the form fields.

function sendform(value1, value2, value3) {
     formData.append('field1', value1);
     formData.append('field2', value2);
     formData.append('field3', value3);
     var xhr = new XMLHttpRequest();
     xhr.open('POST', 'https://www.example.com/formprocessing.php', true);
     xhr.send(formData);
}

Call the function like this using variables or string literals:
var hammy = "hamspter";
sendform( "cat", "dog", hammy );

Or by extracting text from form text fields and passing them as parameters:
sendform("document.getElementById('id1').value",
               "document.getElementById('id2').value",
               "document.getElementById('id3').value"  );