0

I'm using the latest jquery datatables 1.10 plugin

In my ajax call I have the following by standard to pass the data to my asp.net mvc controller

"ajax": {
            "type": "POST",
            "url": '/myUrl/MyMethod/',
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) { return data = JSON.stringify(data); }
        },

I also have a form on my page with various input elements. The id of the form is form1

what I want to do is append all this form's elements with values to the data parameters of my ajax call so my server can pick it up.

I don't want to lose the current data that is being passed by datatables. I want to append the form input elements to this JSON data.

As a workaround currently I pass it the form1 input elements's values individually in the url but this is far from ideal as you can see.

"ajax": {
            "type": "POST",
            "url": '/myUrl/MyMethod/?myselect='+$('#myselect').val(),
            "contentType": 'application/json; charset=utf-8',
            "data": function (data) { return data = JSON.stringify(data); }
        },

Question:

How do I modify the line:

"data": function (data) { return data = JSON.stringify(data); }

to append #form1 inputs without explicitly specifying one input at a time.

dfmetro
  • 4,462
  • 8
  • 39
  • 65
  • you can write an extension of jquery to convert form serialized object to json example is here http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery?answertab=active#tab-top and then in your code "data": function (data) { return {data : JSON.stringify(data), form1:JSON.stringify($('form').serializeObject()) }} – Umer Hayyat Feb 01 '16 at 14:07

1 Answers1

0

You can use the handy .serializeArray function.

So for the jquery code:

var form_data = $("#form1").serializeArray();

//I'm just assuming here that 'table_data' is an existing array with index/values in it from your datatables

 $.each(form_date,function(index,value){
     table_data[value['name']] = value['value']
 })

 //And now both sets of data are merged and you can just pass table_data to your ajax call
Ting Sun
  • 306
  • 2
  • 10