Skip to content Skip to sidebar Skip to footer

Integrate Two Requests Into One Javascript

I have several checkboxes whose values are passed using a POST request. If one checkbox is selected, the value is passed to the POST request. But I already have code that passes P

Solution 1:

You can use .DataTable function to send checkboxes checked value in one request like below:

Try this:

$(function () {   
    var table = $("#portfolio").DataTable({
        "ajax": {
            "url": portfolio_data_url,
            "type": "POST",
            "data": function(d){
                var ids = $('input:checkbox:checked').map(function(){
                        returnthis.value; 
                }).get();
                d.ids = ids; 
            }
        },    
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],    
        "stateSave": true,
        "processing": true,
        "serverSide": true,
        "deferRender": true,
        "language": datatables_language,    
        "order": [[ $(".portfolio thead th").index($(".portfolio thead .appid")), "desc" ]],    
        "columnDefs": [
            {
                "searchable": false,
                "orderable": false,
                "targets": "no-sort"
            }
        ]
    })
});

In Datatable Using the data parameter as a function allows the additional data to send to server

Official Documentation

Note: You will get checked checkboxes value as an array, You can use .join(',') after .get() to send values as comma separated string to use directly in query

Also, when user check any checkbox then we can refresh datatable ajax to send updated checked checkboxes like below:

$("input[type='checkbox']").on("change",function(){
  table.ajax.reload();
});

Solution 2:

It looks like the ajax function youy want to re-use is of DataTable's. It's not a good idea to use the ajax function which is used by some other plugin.

Here the Ajax call you want to Re-Use is used by the function DataTable. Instead of re-using that you can create a wrap-up function which makes ajax request. Every-time if you want to make ajax request you can call that function with specified parameters. Example :

function customAjax(url,data,method,success_message,fail_message){
    $.ajax({
        url:url,
        data:data,
        method:method,
        success:function(response){
            alert(success_message);
        },
        error:function(response){
            alert(fail_message);
        }
    });
}

And call using :

customAjax("xyx.php","username=abc&password=ushfush","POST","Login Successfull","Something went wrong");

Post a Comment for "Integrate Two Requests Into One Javascript"