Submit The Form Using Ajax
I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html
Solution 1:
Nobody has actually given a pure javascript
answer (as requested by OP), so here it is:
functionpostAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = newXMLHttpRequest();
} elseif (window.ActiveXObject) {
req = newActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSONtry {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
returnfalse;
}
req.send(sendstr); // param string only used for POSTif (req.readyState == 4) { // only if req is "loaded"if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return"XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
Solution 2:
What about
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...success: function(response) { ... },
});
Solution 3:
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
functionsend(e,form) {
fetch(form.action,{method:'post', body: newFormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
<formmethod="POST"action="myapi/send"onsubmit="send(event,this)"><inputhiddenname="crsfToken"value="a1e24s1"><inputname="email"value="a@b.com"><inputname="phone"value="123-456-789"><inputtype="submit"></form>
Look on chrome console>network before 'submit'
Solution 4:
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:
<formaction=""method="post"onsubmit="your_ajax_function(); return false;">
Your Name <br/><inputtype="text"name="name"id="name" /><br/><inputtype="submit"id="submit"value="Submit" /></form>
Hope it helps.
Solution 5:
Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method
and action
and grabs all fields inside the form. Support single-dimension array fields, like emails[]
. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case'post':
options.body = JSON.stringify(parsedData);
case'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
Post a Comment for "Submit The Form Using Ajax"