$.ajax({
url: '<?=parseLink("modules/Contacts/output/output.php")?>',
data: {
$('.contacts-block-input-text').each(function(){
id: $(this).attr('id'),
value: $(this).val()
})
},
type: 'post',
success: function(result){
$('.resultMessage').text(result)
}
})
So there will be dynamic amount of input fields and I need to gather all the contacts-block-input-text
values and pass them in the data
field somehow. How could I do this? The given example doesn't work.
$.ajax({
url: '<?=parseLink("modules/Contacts/output/output.php")?>',
data: {
$('.contacts-block-input-text').each(function(){
id: $(this).attr('id'),
value: $(this).val()
})
},
type: 'post',
success: function(result){
$('.resultMessage').text(result)
}
})
So there will be dynamic amount of input fields and I need to gather all the contacts-block-input-text
values and pass them in the data
field somehow. How could I do this? The given example doesn't work.
-
data
accepts a string or an object. I'm not sure exactly what you're trying to achieve with your usage ofeach()
in there. Can you give some details about what data youroutput.php
is expecting to receive. – Rory McCrossan Commented Oct 2, 2015 at 9:56 -
1
Why don't you just serialize these inputs? Set a name attribute to each ones if none already set then use
data: $('.contacts-block-input-text').serialize(),
– A. Wolff Commented Oct 2, 2015 at 9:59
3 Answers
Reset to default 7You have to build an array, collecting your input data:
var myData = [];
$('.contacts-block-input-text').each(function(){
myData.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
Then you can use myData
to pass it to the ajax call.
$.ajax({
url: '<?=parseLink("modules/Contacts/output/output.php")?>',
data: myData,
type: 'post',
success: function(result){
$('.resultMessage').text(result)
}
});
You can simply iterate through your jQuery array, bine the data object, and then pass it to AJAX call:
var d = [];
$(".contacts-block-input-text").each(function() {
d.push({ id: this.id, value: this.value });
});
$.ajax({
data: d
// ...
You may also use $.map()
to generate a data object and pass it over to the ajax
method, as below.
var myData = $('.contacts-block-input-text').map(function() {
return { 'id': this.id, 'value': this.value };
}).get();
$.ajax({
url: '....',
data: myData,
//and so on...
});