[英]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 page with various fields.
为此,我的 html 页面中有一个 HTML 表单,其中包含各种字段。 At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.
在提交时我不使用表单的操作,但我使用自定义 javascript function 在提交表单之前详细说明一些数据。
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
The last line submits the form to the correct page.最后一行将表单提交到正确的页面。 It works fine.
它工作正常。 But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values.
但我想使用 ajax 提交表单,但我不知道该怎么做,因为我不知道如何捕获表单输入值。 anyone can help me?
任何人都可以帮助我吗?
Nobody has actually given a pure javascript
answer (as requested by OP), so here it is:实际上没有人给出纯
javascript
答案(根据 OP 的要求),所以这里是:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
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);
return false;
}
req.send(sendstr); // param string only used for POST
if (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;
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) { ... },
});
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter.您可以向提交按钮添加 onclick 函数,但无法通过按 Enter 提交函数。 For my part, I use this:
就我而言,我使用这个:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
Hope it helps.希望能帮助到你。
You can catch form input values using FormData and send them by fetch您可以使用 FormData 捕获表单输入值并通过 fetch 发送它们
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) { fetch(form.action,{method:'post', body: new FormData(form)}); console.log('We send post asynchronously (AJAX)'); e.preventDefault(); }
<form method="POST" action="myapi/send" onsubmit="send(event,this)"> <input hidden name="crsfToken" value="a1e24s1"> <input name="email" value="a@b.com"> <input name="phone" value="123-456-789"> <input type="submit"> </form> Look on chrome console>network before 'submit'
Here is a universal solution that iterates through every field in form and creates the request string automatically.这是一个通用解决方案,它遍历表单中的每个字段并自动创建请求字符串。 It is using new fetch API.
它正在使用新的 fetch API。 Automatically reads form attributes:
method
and action
and grabs all fields inside the form.自动读取表单属性:
method
和action
并抓取表单内的所有字段。 Support single-dimension array fields, like emails[]
.支持单维数组字段,如
emails[]
。 Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.可以作为通用解决方案来轻松管理具有单一事实来源 - 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>
It's much easier to just use jQuery , since this is just a task for university and you do not need to save code.只使用jQuery会容易得多,因为这只是大学的任务,您不需要保存代码。
So, your code will look like:因此,您的代码将如下所示:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
I would suggest to use jquery for this type of requirement .我建议将 jquery 用于这种类型的要求。 Give this a try
试试这个
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});
I would like to add a new pure javascript
way to do this, which in my opinion is much cleaner, by using the fetch()
API.我想添加一种新的纯
javascript
方法来执行此操作,在我看来,通过使用fetch()
API 更简洁。 This a modern way to implements network requests.这是一种实现网络请求的现代方式。 In your case, since you already have a
form element
we can simply use it to build our request.在您的情况下,由于您已经有一个
form element
我们可以简单地使用它来构建我们的请求。
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest
.正如您所看到的,它比
XMLHttpRequest
使用起来非常干净且不那么冗长。
Nowadays it's a lot easier to accomplish this with plain 'ol JS.如今,使用普通的 'ol JS 来实现这一点要容易得多。
const form = document.querySelector('#your-form'),
data = new URLSearchParams();
for (const pair of new FormData(form)) {
data.append(pair[0], pair[1]);
}
fetch(form.action, {
method: form.method || 'POST',
body: data,
}).then(response => response.json()) // or .text()
.then(data => {
console.log('SUBMITTED', data);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.