Javascript Send Form With No Target

This script sends form data without redirecting. No target, and does not reload the page after sending.

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 file receiving the input needs this line:

<?php
header("Access-Control-Allow-Origin: *");

Caveot option 2 ...

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:

Use Javascript to fill the field and value. The script sends data quietly and there's no redirect to a form landing page.

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use