Reputation: 3629
I wander how send post form data in json format via ajax with JQuery dynamically? For example I'm coding something like this in JQ:
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
and that's good, but in live apps often need to send huge form data and user can dynamically change the fields, so I don't know how many func1, func2, func3 or even func[] will be sent. The q is how to do this dynamically, in old world of an AJAX I could done it by serealizing the form and send to the server. Thanx in advance.
Upvotes: 2
Views: 30048
Reputation: 3629
Yes I can send all the data to the server and in any case it will worked well, example:
$(function() { // on document load
$('#email_form').submit(function() { // set onsubmit event to the form
var data = $('#email_form').serialize(); // serialize all the data in the form
$.ajax({
url: 'testJson.php', // php script to retern json encoded string
data: data, // serialized data to send on server
dataType:'json', // set recieving type - JSON in case of a question
type:'POST', // set sending HTTP Request type
async:false,
success: function(data) { // callback method for further manipulations
for (key in data.email) {
alert(data.email[key]);
}
},
error: function(data) { // if error occured
}
});
return false;
});
});
Upvotes: 5
Reputation: 34628
It is possible to build up dynamic data for an AJAX request but clearly you'll need to know the logic for retrieving that dynamic data. You don't describe this in your question, so in the below example I'm assuming it's based on the number of .user_input
fields in the form (which could be 2, or 10, or whatever). The data is then comprised of field name + field value.
The point is to show dynamic collection of data, that's all.
var ajax_data = {};
$('.user_input').each(function() {
ajax_data[$(this).attr('name')] = $(this).val();
});
$.post('some/url.php', ajax_ata); //etc
Upvotes: 3