php - How to properly get loading text display based on the like button click via jQuery
Solution:
You need to get the loader in relation to the clicked button so instead of using
$('.loader')
Use
$(this).parent().find('.loader')
Same goes for your result message.
The following is a modified click function:
$('.like_post').click(function(e) {
// as you are doing an ajax post here, I would disable the default action of the button:
e.preventDefault();
var $button = $(this); // you use this multiple times so it is more efficient to put it in a var
var id = $button.data('id');
var $buttParent = $button.parent();
var $loader = $buttonParent.find('.loader');
$loader.html('<div style="background:green;color:white;padding:6px;">Please Wait, sending like...</div>').fadeIn(400); // I would change the html before the fadeIn
var rec = {
id: id
};
$.ajax({
type: 'POST',
url: 'like_rec.php',
data: rec,
cache: false,
success: function(msg) {
$loader.hide();
$buttonParent.find('.result_like').html(msg);
}
});
});
Also the center
tag is obsolete so don't use it, instead give your heading a class and use css to centre the text
Answer
Solution:
You're currently targeting every "loader" and every "result_like":
$('.loader').hide();
$('.result_like').html(msg);
Since the elements you want to target are all contained within a single parent <div>
, you can use that for jQuery DOM traversal. Starting from the element being clicked, you can navigate to the containing <div>
and then back down to the target element(s). Something like this:
$(this).parent('div').find('.loader').hide();
$(this).parent('div').find('.result_like').html(msg);
To be repeated anywhere you want to target an element within that "group" of elements. You could also store the containing <div>
in a variable if you prefer, which comes with a tiny performance improvement:
var container = $(this).parent('div');
//...
container.find('.loader').hide();
container.find('.result_like').html(msg);
Source