Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send form data using ajax

I want to send all input in a form with ajax .I have a form like this.

<form action="target.php" method="post" >
    <input type="text" name="lname" />
    <input type="text" name="fname" />
    <input type="buttom" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>

And in .js file we have following code :

function f (form ,fname ,lname ){
    att=form.attr("action") ;
    $.post(att ,{fname : fname , lname :lname}).done(function(data){
        alert(data);
    });
    return true;

But this is not working.i don't want to use Form data .

like image 465
adib16 Avatar asked Feb 09 '14 18:02

adib16


2 Answers

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);
    });
}
like image 94
Mehran Hatami Avatar answered Sep 24 '22 17:09

Mehran Hatami


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()

like image 30
Satpal Avatar answered Sep 24 '22 17:09

Satpal