Question: pass parameter to the server using datatable url property in ajax call

Question

pass parameter to the server using datatable url property in ajax call

Answers 3
Added at 2016-12-29 09:12
Tags
Question

I'm using data tables and on initialization inside ajax request I'm setting url using data- attribute

...
 "ajax": {
            "url": $('#mypage').data('source'),
            "type": "GET",
}...

url embeded in page looks like this

 <divid="mypage" data-source=@Url.Action("CalculateSomething")>
 ...
</dv>

On server side I'm expecting parameter someId

public JsonResult CalculateSomething(int someId)
{
}

my question is:

how can I pass parameter to the server using datatable url property in above ajax call?

update Parameter will come as a value from drop down element inside javascript like

var someId = $('#mydropdown').val();
Answers
nr: #1 dodano: 2016-12-29 10:12

Check documantation on $.ajax. For params you can use data property. Like this:

 url: function(e) { return $('#mypage').data('source'); },
 type: "GET",
 data:
     {
         someId: function(e) { return $('#mydropdown').val(); }, //here is your param
     },
 dataType: "json", //it's better to declare datatype, becouse you using JsonResult in your controller response.
nr: #2 dodano: 2016-12-29 10:12

There are two ways for this, one is you can concatenate in the url like:

 "ajax": {
            "url": $('#mypage').data('source')+"someId="+id,
            "type": "GET",
}

another way is to use data property of ajax :

"ajax": {
            "url": $('#mypage').data('source')+"someId=123",
            "type": "GET",
            "data": function (data) {

                            data.someId= 123;

                        }
}
nr: #3 dodano: 2016-12-29 10:12

IF you will have any other questions in the future you can look it up in the datatables javascript file: dataTables.js:

 * @example
         *   // Add data to the request
         *   $('#example').dataTable( {
         *     "ajax": {
         *       "url": "data.json",
         *       "data": function ( d ) {
         *         return {
         *           "extra_search": $('#extra').val()
         *         };
         *       }
         *     }
         *   } );

I believe in

give a man a fish and you feed him for a day,teach a man to fish and you feed him for a lifetime

Source Show
◀ Wstecz