javascript - getting ajax response when the page loads? -
im creating star rating system , works need have current amount of votes displayed when page loads , im having issues implementing code have work due plugin source code , ajax not language im familiar with.
it puts current votes in element want when click handler activated selecting rating not sure if need add current function or create new 1 , if how not conflict current one.
thanks in advance.
<!doctype html> <html lang="en"> <?php require 'core/init.php'; ?> <head> <meta charset="utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <div> <table> <tr> <td><div id="randomtest" class="star"></div></td> <td id="cvotes"></td> </tr> </table> </div> <script type="text/javascript" src="star/assets/js/jquery.raty.min.js"></script> <script type="text/javascript"> $(function() { $.fn.raty.defaults.path = 'star/assets/img'; $('.star').raty({ half : true, number : 5, score : 3, click: function(score, evt) { /*implement click once * $(this).find('img').unbind('click'); */ var pid=$(this).prop('id'); $.ajax({ url: 'rate.php', data: { score: score, pid:pid }, type: 'post', success: function (data) { $('#cvotes').empty().append(data + ' votes.'); // needs done on page load too! }, error: function (jxhr, msg, err) { $('#cvotes').append('<li style="color:red">' + msg + '</li>'); } }); } }); }); </script> </body> </html>
you should aware since using #cvotes unique element on page every result appear on single element no matter how many .star elements have on page.
for rating data loaded @ right time have ajax request after initiate raty plugin.
you should inside plugin code, doing on pageready should work
<script type="text/javascript"> $(function() { function onrateresultssuccess(data) { $('#cvotes').empty().append(data + ' votes.'); } function onrateresultserror(data) { $('#cvotes').append('<li style="color:red">' + msg + '</li>'); } $.fn.raty.defaults.path = 'star/assets/img'; $('.star').raty({ half : true, number : 5, score : 3, click: function(score, evt) { /*implement click once * $(this).find('img').unbind('click'); */ var pid=$(this).prop('id'); $.ajax({ url: 'rate.php', data: { score: score, pid:pid }, type: 'post', success: onrateresultssuccess, error: onrateresultserror }); } }); // should inside raty plugin init click handler // every .star element $('.star').each(function () { var pid=$(this).prop('id'); // use http $.get('rate.php', { pid:pid } ,onrateresultssuccess).fail(onrateresultserror); }); }); </script>
Comments
Post a Comment