Top Poster
#1 ramon fincken 400
#2 Site admin 3
#3 Ber|Art 2
#4 braddmark 1
#5 accentmedia 1
#6 Xarzu 1
#7 pEcosespedex 1
#8 khadish 1
#9 moxxx 1
#10 nistelrock 1
[snipplet] AJAX rating system



Rating : 4 / 5

 
Post new topic   Reply to topic    Ramonfincken.com Forum Index -> PHP coding
Beta
Want to be notified by email when this topic gets a reply?  
View previous topic :: View next topic  
Author Message
ramon fincken
Site's programmer

Get a free globally recognized avatar
It's free!


Joined: 03 Aug 2007
Posts: 400
Location: A'dam/Diemen, The Netherlands

PostPosted: Sat Mar 22, 2008 9:13 pm    Post subject: [snipplet] AJAX rating system Reply with quote

By multiple requests here is a framework/snipplet for a simple yet working AJAX rating system for example articles..

See the rating in live action above the topics on this board !


I presume that you have some JS/SQL knowledge to do this, but it should be managable Wink

Features:

+ Max 1 rating per session per article
+ AJAX request and update
+ Easy average and toplist ( toplist is at the bottom of this post )
+ Default rating for newly created articles is 3, I presume rating goes from 1,2,3,4,5

Some notes beforehand:
I presume your primary key is "news_id", and that you have defined [ define('NEWS_TABLE','article_table'); ]
Next, you are free to find a nice "wating" image while the request is waiting for a response. [ JS code: var loading = './img/uploading.gif'; ]


  • Step1
    SQL
    Add this to your article table
    `news_rating` int(11) default '3'
    `news_ratingcount` int(11) default '1'

  • Step2
    Javascript
    Code:
    <script type="text/javascript" src="ajax.js"></script>


    Javascript source:
    Code:
    /*
     Simple AJAX rating system
     @author Ramon Fincken, Websitefreelancers.nl Ramonfincken.com
     *************************************
    */
    var loading = './img/uploading.gif';

    var url_ajax1 = "inc_rating.php?news_id=";
    var request1 = false;

    /*
     REQUEST 1
     *************************************
    */

    function create_request()
    {

       var objXMLHttp=null;
       if (window.XMLHttpRequest)
       {
          objXMLHttp = new XMLHttpRequest();
          if (objXMLHttp.overrideMimeType)
          {
             objXMLHttp.overrideMimeType('text/xml');
          }
       }
       else if (window.ActiveXObject)
       {
          try
          {
             objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch (e)
          {
             try
             {
                objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
             }
             catch (e)
             {
                }
            }
       }
       return objXMLHttp;
    }
    function makeRatingRequest()
    {
       var news_id = document.getElementById('news_id').value;
       var inputvalue = document.getElementById('ratingselect').value;

       if(!validateinput(inputvalue))
       {
          return;
       }
       document.getElementById('loading').innerHTML = '<img src="'+loading+'">';

       request1 = create_request();

       if (!request1)
       {
          alert('Giving up :( Cannot create an XMLHTTP instance');
          return false;
       }
       request1.onreadystatechange = alertContents1;
       request1.open('GET', url_ajax1 + escape(news_id) + '&rating=' + escape(inputvalue), true);
       request1.send(null);
       document.getElementById('loading').innerHTML = '';
    }

       function alertContents1()
       {
          if (request1.readyState == 4)
          {
             if (request1.status == 200)
             {
                document.getElementById('ratingresult').innerHTML = request1.responseText;
             }
             else
             {
                alert(request1.readyState+ 'There was a problem with the request.err1');
             }
          }
       }
    /*
     REQUEST 1
     *************************************
    */

       function validateinput(input)
       {
        if (input > '6' || input < '0')
        {
           alert('No valid rating');
           return false;
        }
        return true;
       }



  • Step3:
    Rating AJAX source:
    Code:
    <?php
    /*
     * inc_rating.php
     *
     * Ramon Fincken
     * WebsiteFreelancers.nl / CreativePulses.nl
     */
    @session_start();


    /*
    * TODO: MAKE CONNECTION WITH YOUR DATABASE HERE
    */

    $news_id = intval($_GET['news_id']);


    if (isset ($_SESSION['rating'][$news_id]) && isset($_GET['rating']) && intval($_GET['rating']) > 0 && $_GET['rating'] <= 5) {
       echo '<br/>You cannot vote twice!';
    }
    if (!isset ($_SESSION['rating'][$news_id]) && isset($_GET['rating']) && intval($_GET['rating']) > 0 && $_GET['rating'] <= 5) {
       // First time vote this session 
       $sql = "UPDATE " . NEWS_TABLE . " SET news_rating = news_rating+".intval($_GET['rating']).",news_ratingcount = news_ratingcount+1 WHERE news_id = " . $news_id . " LIMIT 1";
       $result = mysql_query($sql);
       $_SESSION['rating'][$news_id] = $news_id;
       echo '<br/>Rating stored!';
    }

    // Show Rating
    $sql = "SELECT news_rating AS rating, news_ratingcount AS aantal FROM " . NEWS_TABLE . " WHERE news_id = " . $news_id . " LIMIT 1";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
       echo '<br/>Rating : '.(max(1,round(($row['rating']/$row['aantal']),1)));
    }
    ?>



  • Step4:
    SHOW RATING && LET USER RATE
    Code:
          echo '<div id="loading">';
          echo '</div>';
          echo '<div id="ratingresult">';
          include ('inc_rating.php');

          echo '<br />';
          echo '<input type="hidden" value="' . intval($_GET['news_id']) . '" name="news_id" id="news_id">';

          echo '<SELECT name="ratingselect" id="ratingselect" onChange="makeRatingRequest();">';
          echo '<OPTION value="0">Rate this article</OPTION>';
          $i = 1;
          while ($i < 6) {
             echo '<OPTION value="' . $i . '">' . $i . '</OPTION>';
             $i++;
          }
          echo ' </SELECT>';
          echo '</div>';


    • Important, adjust the intval($_GET['news_id']) to a numeric primary key for your article.
      echo '<input type="hidden" value="' . intval($_GET['news_id']) . '" name="news_id" id="news_id">';




  • Optional, toplist SQL code, be sure to have a LIMIT setting ( $settings['max_articles_home'] ) !
    Code:
    $sql = "SELECT *, news_rating AS rating, news_ratingcount AS aantal, (news_rating/news_ratingcount) AS deling FROM " . NEWS_TABLE . " HAVING deling > 2.5 ORDER BY deling DESC, news_ratingcount DESC LIMIT " . $settings['max_articles_home'];


  • Note1:
    Rating 1,2,3,4,5 comes back in the following bits and bytes:
    Code:
          echo '<SELECT name="ratingselect" id="ratingselect" onChange="makeRatingRequest();">';
          echo '<OPTION value="0">Rate this article</OPTION>';
          $i = 1;
          while ($i < 6) {
             echo '<OPTION value="' . $i . '">' . $i . '</OPTION>';
             $i++;
          }
          echo ' </SELECT>';


    In the JS source:
    Code:
       function validateinput(input)
       {
        if (input > '6' || input < '0')
        {
           alert('No valid rating');
           return false;
        }
        return true;
       }

    And of course (twice) in the serverside rating file:
    Code:
    intval($_GET['rating']) > 0 && $_GET['rating'] <= 5


  • Note2:
    I provided a simple XMLHTTP request, feel free to replace function create_request() with your own request function.


Last edited by ramon fincken on Mon Jul 07, 2008 12:14 pm; edited 5 times in total
Back to top
View user's profile Send private message Visit poster's website
Google adsense
Advertisement





PostPosted: Sat Mar 22, 2008 9:13 pm    Post subject: [snipplet] AJAX rating system

Advertisement
Back to top
GravityForms
Advertisement





PostPosted: Sat Mar 22, 2008 9:13 pm    Post subject: [snipplet] AJAX rating system

Advertisement
Gravity Forms Plugin for WordPress
Back to top
ramon fincken
Site's programmer

Get a free globally recognized avatar
It's free!


Joined: 03 Aug 2007
Posts: 400
Location: A'dam/Diemen, The Netherlands

PostPosted: Sat Mar 22, 2008 9:13 pm    Post subject: [snipplet] AJAX rating system part 2 Reply with quote

RESERVED

Last edited by ramon fincken on Sat Mar 22, 2008 9:14 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website
Post new topic   Reply to topic    Ramonfincken.com Forum Index -> PHP coding All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
General forums
The world of freelance
Programming
Other projects
Poll
I love gifts

Yes goodies and presents! [3]
No but I love polls ! [1]

Related google ads