Saswat
Saswat

Reputation: 12846

Conditional parameters for AJAX function

I have a piece of code which is like this..

    var v = $('#time_type').val();

    /* ajax call to fetch limit no. of data continuously */
    ajaxcall_continue = $.post("ajax.php",
            {   
            'time_type':v,'func':'show_datatable',
            'start_row':outer_start_row,'limit':outer_limit
            },
            function(response)
            {
                /*---- function body ----*/
            },'json');

now here will be a condition like

var v = $('#time_type').val();
if(v == 'custom')
{
     var st = $('#start_time').val();
     var en = $('#end_time').val();
     ajaxcall_continue = $.post("ajax.php",
                {   
                'time_type':v,'start_time':st,'end_time':en,'func':'show_datatable',
                'start_row':outer_start_row,'limit':outer_limit
                },
                function(response)
                {
                    /*---- function body ----*/
                },'json');
}
else
{
     ajaxcall_continue = $.post("ajax.php",
                {   
                'time_type':v,'func':'show_datatable',
                'start_row':outer_start_row,'limit':outer_limit
                },
                function(response)
                {
                    /*---- function body ----*/
                },'json');
}

But the issue is, I don't want two write two separate $.post function in the if else statement.

Better I want to make two separate parameter list based on the condition and use them in the $post function.

I can't find the procedure to do this.

Upvotes: 0

Views: 1709

Answers (2)

Abid Hussain
Abid Hussain

Reputation: 102

Are you able to the same functionality by using variable?

var parameter = ''
var v = $('#time_type').val();
if(v == 'custom')
{
 var st = $('#start_time').val();
 var en = $('#end_time').val();
 parameter = "{'time_type':v,'func':'show_datatable','start_row':outer_start_row,'limit':outer_limit }";
}
else
{
    parameter = " {'time_type':v,'func':'show_datatable','start_row':outer_start_row,'limit':outer_limit}"
}

ajaxcall_continue = $.post("ajax.php",parameter,
            function(response)
            {
                /*---- function body ----*/
            },'json');

Upvotes: 1

user2575725
user2575725

Reputation:

Try this way out:

var options = {};
options.url = "example.com";
options.data = {};
if(condition) {
    options.data.param1 = 'abc';
    ...
} else {
    options.data.param2 = 'xyz';
    ...
}
...
$.post(options);//only once !

Upvotes: 3

Related Questions