Send form data using ajax
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
In your function form
is a DOM object, In order to use attr()
you need to convert it to jQuery object.
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, {fname : fname , lname :lname}).done(function (data) {
alert(data);
});
return true;
}
With .serialize()
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, $(form).serialize() ).done(function (data) {
alert(data);
});
return true;
}
Additionally, You can use .serialize()
$.ajax({
url: "target.php",
type: "post",
data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
alert(data);
});