Bobby WW
Bobby WW

Reputation: 45

How to use single jQuery ajax post with multiple functions inputting data

I am quite new to jQuery and having trouble with below code. It gets values from 3 sets of checkboxes and uses the values for each in the ajax post.

The ajax post is identical each time. It all works perfectly, but obviously not coded well.

How can I just have the ajax post once but have the 3 functions providing data. Any help apppreciated very much. Spent ages trying.

$('.filters-price input[type=checkbox]').click(function(){
    var d1x = 'price';

    $.ajax({
        type:'POST',
        url:'Filter.php',
        data:'id='+d1x,
        success:function(html){
            $('#myDiv').replaceWith(html);
        }
    });
});

$('.filters-duration input[type=checkbox]').click(function(){
    var d1x = 'duration';

    $.ajax({
        type:'POST',
        url:'Filter.php',
        data:'id='+d1x,
        success:function(html){
            $('#myDiv').replaceWith(html);
        }
    });
});

$('.filters-rating input[type=checkbox]').click(function(){
    var d1x = 'rating';

    $.ajax({
        type:'POST',
        url:'Filter.php',
        data:'id='+d1x,
        success:function(html){
            $('#myDiv').replaceWith(html);
        }
    });
});

Upvotes: 1

Views: 42

Answers (2)

Heretic Monkey
Heretic Monkey

Reputation: 12114

I'd change the approach. First, give all of the filters-* elements the same (additional) class (filters in this example) and add a data- attribute with the dlx value you need to pass to your service (data-filter-dlx in this example).

Then all you need is a single function:

$('.filters input[type="checkbox"]').on('click', function(e) {
  var dlx = $(this).attr('data-filter-dlx');

  $.ajax({
    type:'POST',
    url:'Filter.php',
    data:'id='+d1x,             
    success:function(html){     
      ('#myDiv').replaceWith(html);
    }
  });  
});

Upvotes: 1

krishna
krishna

Reputation: 1029

Please try this.

$('.filters-price input[type=checkbox]').click(function(){
    var d1x = 'price';

    call_ajax(d1x);
});

$('.filters-duration input[type=checkbox]').click(function(){
    var d1x = 'duration';

    call_ajax(d1x);
});

$('.filters-rating input[type=checkbox]').click(function(){
    var d1x = 'rating';
    call_ajax(d1x);
});

// Create a function
function call_ajax(data_id){
   $.ajax({
        type:'POST',
        url:'Filter.php',
        data:'id='+data_id,
        success:function(html){
            $('#myDiv').replaceWith(html);
        }
    });
}

Upvotes: 0

Related Questions