index.php
<form method="post" action="process.php" >
Firstname: <input type="text" name="firstname" />
<br />
Lastname: <input type="text" name="lastname" />
<br />
Description: <textarea name="description" rows="10" cols="50" ></textarea>
<br />
Gender:
<input type="radio" name="gender" value="male" checked /> Male
<input type="radio" name="gender" value="female" /> Female
<br />
<hr />
<input type="submit" value="Submit" />
</form>
display result form server
<div id="output"></div>
get formHTML element and add onsubmit event, and create formData, then call ajax function with arguments formHTML, formData and output display ("#output")
<script>
/* submit form */
document.querySelector( "form" ).addEventListener( "submit", function (event) {
event.preventDefault(); // return false
var formHTML = event.target; // this
console.log( formHTML ); // formHTML element
// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
var formData = new FormData( formHTML );
console.log( formData );
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// https://www.w3schools.com/xml/xml_http.asp
// https://www.w3schools.com/js/js_ajax_http.asp
/* AJAX request */
ajax( formHTML, formData, "#output" ); // ajax( form, data destination )
});
</script>
ajax function
<script>
function ajax( form, data, destination )
{
if (window.XMLHttpRequest)
{
var xhr = new XMLHttpRequest(); /* code for modern browsers */
}
else
{
var xhr = new ActiveXObject("Microsoft.XMLHTTP"); /* code for old IE browsers */
}
xhr.open( form.method, form.action, true ); // ( "post", "process.php", true )
xhr.send( data );
xhr.onreadystatechange = function () {
if ( this.readyState == 4 && this.status == 200 )
{
document.querySelector( destination ).innerHTML = this.responseText;
}
};
}
</script>
process.php
echo "<pre>";
var_dump($_POST);
echo "</pre>";
Demo repl.it
Top comments (0)