Have not found anyhing on stack
My sorting method is:
if($_GET['f1']=='ASC')
{
$order = ' ORDER BY clients.name ASC ';
$f1 = '<button type="button" id="DESC"><i ></i></button>';
}
elseif($_GET['f1']=='DESC')
{
$order = ' ORDER BY clients.name DESC ';
$f1 = '<button type="button" id="ASC"><i ></i></button>';
}
else
{
$f1 = '<button type="button" id="ASC"><i ></i></button>';
}
The same logic I have for f2, f3 and f4
My AJAX for f1 is like:
$(document).on("click",".f1",function(){
let id = $(this).attr('id');
$.ajax({
method:'GET',
url:'ajax.php?x=clients',
data:{f1:id},
success:function(response){
$('#data').html(response);
}
})
})
Everythign works properly but I would like to make sorting for all methods (f1,f2,f3,f4) using one ajax function
Please advise the best way to make it without total modification of any of the methods
CodePudding user response:
You can do this with a few small changes I think:
- Make all the search buttons have a single class in common, and store the type of search and the direction as data-attributes (don't use
id="ASC"
like that because IDs must be unique in a HTML document, and clearly you could end up with more than one like that, across the 4 methods). - handle click on the single class, and fetch the data attributes of the clicked button to determine the settings to put into the AJAX call.
For example:
<button type="button" data-sort="clients" data-direction="DESC">
and
<button type="button" data-field="surname" data-direction="ASC">
Then in the JS: .
$(document).on("click",".sort",function(){
let direction = $(this).data('direction');
let field = $(this).data('field');
$.ajax({
method:'GET',
url:'ajax.php',
data: {"field": field, "direction": direction},
success:function(response){
$('#data').html(response);
}
})
});
Obviously you should then amend your PHP to look for $_GET['field'] and
$_GET['direction']`, to match the AJAX parameter names (I felt these were a lot easier to understand than "x" and "f1", which are pretty meaningless, but you may disagree and change them back if you wish).
CodePudding user response:
You can use wildcard on class
before send data.
$("[class^='f']").on('click', function() {
let id = $(this).attr('id'); //get id
let cls = $(this).attr('class'); // get f1,f2 as class name
// On ajax call
$.ajax({
method: 'GET',
url: 'ajax.php?x=clients',
data: {
cls: id
},
success: function(response) {
$('#data').html(response);
}
});
});