10

I have the following snippet where I am serializing form data and posting it via ajax. I have come across a situation where I need to add additional data. In this case I need to add a comma separated array called 'selectedHours'. Is this possible?

I am creating 'selectedHours' through as shown below where it creates an array of list items with the class 'hour-selected'. There are no form values, inputs, etc used in this aspect.

var selectedHours = [];
$('.hour-selected').each(function(k,v) {
    selectedHours.push($(v).text());
});

$.ajax({ 
    type: 'post',
    url: '/process/somepage.php',
    data: $form.serialize(),
    dataType : 'json'
}).done(function (response) {
... and so on...
user756659
  • 3,372
  • 13
  • 55
  • 110

2 Answers2

21

try this:

$.ajax({ 
    type: 'post',
    url: '/process/somepage.php',
    data: $form.serialize() + '&hours=' + JSON.stringify(selectedHours),
    dataType : 'json'
}).done(function (response) {
... and so on...

data sended are just a URL encoded string. You can append other value with a simple concatenation.

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
  • 1
    I had no idea it was that simple... learned one more thing with ajax... thanks! Is JSON.stringify necessary? selectedHours already returns 1pm,4pm,11pm for example. – user756659 Mar 05 '14 at 20:41
4

Perhaps a better solution to this might be to use jQuery's serializeArray, as suggested by this answer:

var data = $form.serializeArray();
data.push({name: 'hours', value: selectedHours});

$.post('/process/somepage.php', data).done(doSomething);

This solution might be preferable because it avoids manually constructing a serialized data string, instead opting to passing the data on for jQuery to deal with.

Laef
  • 1,086
  • 2
  • 11
  • 27