Huander Huander - 2 months ago 18
jQuery Question

Json form data as dynamic submit

The Ajax post works when passing the predefined data as follow:

//var data = {"name" : "Testing", "email" : "testing@gmail.com", "cpf" : "9876543210"};

But I am unable to pass the data dynamically from the form.

Please help me figure this out.

Post function

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

$(function() {
$("#post").click(function() {
$("#dataIn").text(JSON.stringify($("form").serializeObject()));

$(function() {
//var data = {"name" : "Testing", "email" : "testing@gmail.com", "cpf" : "9876543210"};
var data = ("#dataIn");
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
//data: JSON.stringify(data),
contentType: "application/json",
});
});
});
});


The Form

<form action="" method="post" class="form-inline">

<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">

<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">


<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">

<button id="post" type="submit" type="button">Add </button>
</form>

<p >Json Result</p>
<pre id="dataIn" ></pre>




I am not sure if I have to serialize the form or if the JSON.stringify(data) can already do this.

below code works perfectly:

Non dynamically, But working

$("#post1").click(function(){
var data = {"name" : "Testing", "email" : "testing@gmail.com", "cpf" : "9876543210"};

$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: JSON.stringify(data),
contentType: "application/json",
});
console.log("Loaded");
});


Thank you.

Answer

The best solution I could think of at the moment:

$(function() {
    $("#post").click(function() {
        var data = JSON.stringify($("form").serializeObject());
        $("#dataIn").text(data);
        $(function() {
            $.ajax({
                type: "POST",
                url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
                data: data,
                contentType: "application/json",
            });
        });
    });
});

You don't need to use JSON.stringify() twice, because you already did it on .serializeObject() returned value. Next you print it to your #dataIn container and send it via ajax request.

Comments