Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST"> <input type="text" name="name" value="previousValue"/> <button type="submit" name="action" value="dosomething">Update</button> </form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest
. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } function demoRequest() { var request = getHttpRequest(); request.onreadystatechange=function() { if (request.readyState == 4 && request.status == 200) { console.log("Response Received"); } } request.open("POST","post-handler.php",true); request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); request.send("action=dosomething"); }
So for example, say the javascript method demoRequest()
was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest
?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form"> <input type="text" name="name" value="previousValue"/> <button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button> </form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) { evt.preventDefault(); // Do something updateProperties(); return false; });
To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message. You also need to specify the data type using the Content-Type: application/x-www-form-urlencoded request header.
The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. The formtarget attribute overrides the target attribute of the <form> element. Note: The formtarget attribute is new for the <input> element with type="submit" in HTML5.
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format. You can either iterate all input elements or get specific ones by calling document.getElementById()
.
Warning: You have to use encodeURIComponent()
for all names and especially for the values so that possible &
contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id"); var inputData = encodeURIComponent(input.value); request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData
objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData
object from an existing form and we can send it it directly to XMLHttpRequest
's method send():
var formData = new FormData( document.getElementById("my-form-id") ); xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/> <script> "use strict"; function submitForm(oFormElement) { var xhr = new XMLHttpRequest(); xhr.onload = function(){ alert(xhr.responseText); } xhr.open(oFormElement.method, oFormElement.getAttribute("action")); xhr.send(new FormData(oFormElement)); return false; } </script> </head> <body> <form method="POST" action="post-handler.php" onsubmit="return submitForm(this);" > <input type="text" value="previousValue" name="name"/> <input type="submit" value="Update"/> </form> </body> </html>
This snippet is basic and cannot use GET
. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With