I adjust the heart rate with a click counter (like on Twitter). The client side looks like this:
<script> $(document).ready(function() { $('.rate_widget').each(function(i) { var widget = this; var out_data = { widget_id : $(widget).attr('id'), fetch: 1 }; $.post( 'ratings.php', out_data, function(INFO) { $(widget).data('fsr', INFO); set_votes(widget); }, 'json' ); }); $('.ratings_stars').hover( // Handles the mouseover function() { $(this).prevAll().andSelf().addClass('ratings_over'); $(this).nextAll().removeClass('ratings_vote'); }, // Handles the mouseout function() { $(this).prevAll().andSelf().removeClass('ratings_over'); // can't use 'this' because it wont contain the updated data set_votes($(this).parent()); } ); // This actually records the vote $('.ratings_stars').bind('click', function() { var star = this; var widget = $(this).parent(); var clicked_data = { clicked_on : $(star).attr('class'), widget_id : $(star).parent().attr('id') }; $.post( 'ratings.php', clicked_data, function(INFO) { widget.data('fsr', INFO); set_votes(widget); }, 'json' ); }); }); function set_votes(widget) { var votes = $(widget).data('fsr').total_points; if (votes > 0) { $(widget).find('.star_1').andSelf().addClass('ratings_vote'); } $(widget).find('.total_votes').text(votes); } // END FIRST THING </script> When you just click on the hearts, everything happens normally. But at the beginning, at the initial loading of the states of the hearts and counters, there are brakes. There are quite a lot of objects with the .rate_widget class; this generates a large number of requests and takes a lot of time.
How to collect all requests in one, then process them in a pack on the server, return here and put it in places?
Here is the entire server (ratings.php):
<?php $rating = new ratings($_POST['widget_id']); isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote(); class ratings { var $data_file = './ratings.data.txt'; private $widget_id; private $data = array(); function __construct($wid) { $this->widget_id = $wid; $all = file_get_contents($this->data_file); if($all) { $this->data = unserialize($all); } } public function get_ratings() { if($this->data[$this->widget_id]) { echo json_encode($this->data[$this->widget_id]); } else { $data['widget_id'] = $this->widget_id; $data['total_points'] = 0; echo json_encode($data); } } public function vote() { $ID = $this->widget_id; if($this->data[$ID]) { $this->data[$ID]['total_points'] += 1; } else { $this->data[$ID]['total_points'] = 1; } file_put_contents($this->data_file, serialize($this->data)); $this->get_ratings(); } }