how to post form data in ajax way and without jquery or other libraries.
I want to define a ajaxForm function, which could serialize the form data and AJAX post, and then callback by javascript.
If I has form below:
<form action="url" method="POST">
<table><tr><td>label...</td><td><input name="input1" type="text"/></td></tr><tr><td>label...</td><td><input name="input2" type="checkbox"/></td></tr><tr><td>label...</td><td><select name="input3"><options....></select></td></tr></table></form>
and I got the form element by javascript, and then I pass the form element and callback function to ajaxForm(form, callback) function.
Any one could give a example of that ? Thanks a lot....
update : My most problem is how to serialize form data ?
update again: Thanks for all your response. Problem resolved.
I have migrated the jquery form plugin to pure javascript. and I am glad to share it with you guys.
https://github.com/guileen/ajaxform.js
button.onclick = function(){
ajaxForm(form, function(xmlhttp){
alert(xmlhttp.status);
alert(xmlhttp.responseText);
});
}
Here's an example of how you can implement the ajaxForm function in pure JavaScript:
function ajaxForm(form, callback) { var xhr = new XMLHttpRequest(); xhr.open("POST", form.action, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { callback(xhr); } }; var formData = new FormData(form); var data = []; for (var key of formData.keys()) { data.push(encodeURIComponent(key) + "=" + encodeURIComponent(formData.get(key))); } xhr.send(data.join("&")); }
The formData object is created using the FormData constructor and passed the form element as its argument. This object provides an API to get the key-value pairs from the form, which we then join into a string and send as the request body to the server.
The callback function is invoked when the response from the server is received and processed, and it's passed the XMLHttpRequest object as its argument.