class undefined probably caused by a javascript function

Discussion in 'JavaScript' started by co.ador, Jul 24, 2009.

  1. #1
    Part 1 of this post

    I have tested the file i am working on firebug and it's html output result as:
    undefined can anybody and i have wondered what can be done to define?

    <td>
    <ul id="Torpedo" class="undefined">
    <li class="one">
    <a title="1 Star" href="javascript:RateItem('Torpedo', 1);">1</a>
    </li>
    <li class="two">
    <a title="2 Stars" href="javascript:RateItem('Torpedo', 2);">2</a>
    </li>
    <li class="three">
    <a title="3 Stars" href="javascript:RateItem('Torpedo', 3);">3</a>
    </li>
    <li class="four">
    <a title="4 Stars" href="javascript:RateItem('Torpedo', 4);">4</a>
    </li>
    <li class="five">
    <a title="5 Stars" href="javascript:RateItem('Torpedo', 5);">5</a>
    </li>
    </ul>
    </td>
    HTML:
    I have come to some conclusion but still not sure.

    Part 2 of this post

    below is an illustrated example.

    this is a rating system that I am working on Right now the nostar row stars appear when there is not any rating or any user or IP.

    Stage 1 before user x click there is not votes, in other words the item will be rated for the first time and the stars appear blank

    [​IMG]



    Stage 2
    The user x clicked in one of the star in this Case Nike Air Jordan item was
    [​IMG]

    Stage 3
    Then stage 3 will only be possible if i click the refresh button of the firefox browser.

    [​IMG]


    The final result should be from stage 1 to stage 3 in other words having stage 3 without having to click the refresh button in the browser.


    Part 3 of this post


    Below are all the files that compose or form the working system I am working at this moment. I will star with the rating.class.php file. In this file rating.class.php there is a method called the OutputRating and it is in charge to either present the empty row of star showed in stage 1 in the illustration above inside Part 2 of this post which will appear if the user hasn't rated the item or the row of star rated by that ip which will show the rate of that user or the average of all the ips that has rated that item.

    Rating.class.php
    <?php
    	class Rating
      {
        ## PRIVATE VARIABLES
        ## END PRIVATE VARIABLES
    
        ## PUBLIC METHODS
          // Output the Rating information
          // Returns a string of HTML
          public static function OutputRating($varItem)
          {
            // Verify $varItem was provided
            if ($varItem != null && strlen(trim($varItem)) != 0)
            {
              // Check if Magic QUotes is ON
              if (!get_magic_quotes_gpc())
              {
                $varItem = addslashes($varItem);
              }
              
              // Information for the Output
              $averageStars = Rating::CalculateAverageRating($varItem);
              
              // Check to see that the user has not already rated this item
              if (Rating::CheckRatingsByIp($varItem) == 0)
              {
                $classes      = "rating" . Rating::ShowStars($averageStars);
                
                // Write Output HTML for the Rating Data
                $output  = "\r\n";
                $output .= "<ul class=\"{$classes}\" id=\"{$varItem}\">\r\n";
                $output .= "  <li class=\"one\"><a   href=\"javascript:RateItem('{$varItem}', 1);\" title=\"1 Star\">1</a></li>\r\n";
                $output .= "  <li class=\"two\"><a   href=\"javascript:RateItem('{$varItem}', 2);\" title=\"2 Stars\">2</a></li>\r\n";
                $output .= "  <li class=\"three\"><a href=\"javascript:RateItem('{$varItem}', 3);\" title=\"3 Stars\">3</a></li>\r\n";
                $output .= "  <li class=\"four\"><a  href=\"javascript:RateItem('{$varItem}', 4);\" title=\"4 Stars\">4</a></li>\r\n";
                $output .= "  <li class=\"five\"><a  href=\"javascript:RateItem('{$varItem}', 5);\" title=\"5 Stars\">5</a></li>\r\n";
    			$output .= "</ul>\r\n";
              }
              else
              {
                $classes      = "rated " . Rating::ShowStars($averageStars);
    			
                
                // Write Output HTML for the Rating Data
                $output  = "\r\n";
                $output .= "<ul class=\"{$classes}\" id=\"{$varItem}\">\r\n";
                $output .= "  <li class=\"one\">1</li>\r\n";
                $output .= "  <li class=\"two\">2</li>\r\n";
                $output .= "  <li class=\"three\">3</li>\r\n";
                $output .= "  <li class=\"four\">4</li>\r\n";
                $output .= "  <li class=\"five\">5</li>\r\n";				            		
                $output .= "</ul>\r\n";
              }
            }
            else
            {
              $output = "";
              // This is a major issue. NO information can be retrieve if an item name is not passed.
              Error::LogError("Variable Missing", "You must provide the item name for this function to find the average.");
            }
            
            return $output;
          }
          
          // Rate an Item
          // Returns the name/value pair of new class names and the item name
          public static function RateItem($varItem, $varRating, $varClasses)
          {
            $newClassNames = $varClasses;
            
            // Verify $varName was provided
            if ($varItem != null && strlen(trim($varItem)) != 0
              && $varRating != null && strlen(trim($varRating)) != 0 && is_numeric($varRating) 
              && $varClasses != null && strlen(trim($varClasses)) != 0)
            {
              // Check if Magic Quotes is ON
              if (!get_magic_quotes_gpc())
              {
                $varItem = addslashes($varItem);
              }
              
              // Check to see that the user has not already rated this item
              if (Rating::CheckRatingsByIp($varItem) == 0)
              {
                $ipAddress = $_SERVER['REMOTE_ADDR'];
                
                Database::ExecuteQuery("INSERT INTO `rating` (`item_name`, `rating`, `ip_address`, `date_rated`) VALUES ('{$varItem}', {$varRating}, '{$ipAddress}', NOW())", "InsertRating");
                Database::FetchResults("InsertRating");
                Database::FreeResults("InsertRating");
                Database::RemoveSavedResults("InsertRating");
                
                // Information for the Output
                $averageStars  = Rating::CalculateAverageRating($varItem);
                $newClassNames = "rated " . Rating::ShowStars($averageStars);
              }
            }
            else
            {
              // This is a major issue. NOT enough information was sent to log the item
              Error::LogError("Variable(s) Missing", "You must provide all of the information to log the rating of this item.");
            }
            
            // Build Name/Value Pair to return
            $nameValue = "classes={$newClassNames}&item={$varItem}";
            return $nameValue;
          }
        ## END PUBLIC METHODS
        
        ## PRIVATE METHODS
          // Calculate Average Rating
          // Returns the number of stars to show
          private static function CalculateAverageRating($varItem)
          {
            $averageStars = 0;
            
            // Query Average Rating for a specific Item
            Database::ExecuteQuery("SELECT AVG(`rating`) AS `averageRating` FROM `rating` WHERE `item_name`='{$varItem}'", "AverageRating");
            $results = Database::FetchResults("AverageRating");
            Database::FreeResults("AverageRating");
            Database::RemoveSavedResults("AverageRating");
            
            // Round the Average into a Whole Number
            if (sizeof($results) == 1)
            {
              if ($results[0]['averageRating'] != null)
              {
                $averageStars = round($results[0]["averageRating"], 0);
              }
            }
            else
            {
              // This is simply a warning, as it isn't vital if no results were found, as the item may be new.
              Error::LogWarning("Rating Data Missing", "No entries were found for '{$varName}', this might be the first entry.");
            }
            
            return $averageStars;
          }
          
          // Show Stars
          // Returns the class information for the number of stars to show
        private static function ShowStars($varStars)
    {
        $aStars = array(
            1    =>    'onestar',
            2    =>    'twostar',
            3    =>    'threestar',
            4    =>    'fourstar',
            5    =>    'fivestar'
        );
        return (true === array_key_exists((integer)$varStars, $aStars)) ? $aStars[(integer)$varStars] : 'nostar' ;
    } 
    
          // Check Ratings By IP Address
          // Returns the number of ratings for an item by an ip address
          private static function CheckRatingsByIp($varItem)
          {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
            
            Database::ExecuteQuery("SELECT COUNT(*) AS `totalRatings` FROM `rating` WHERE `item_name`='{$varItem}' AND `ip_address`='{$ipAddress}'", "AlreadyRated");
            $results = Database::FetchResults("AlreadyRated");
            Database::FreeResults("AlreadyRated");
            Database::RemoveSavedResults("AlreadyRated");
            
            // Check to see that the user has not already rated this item
            if ($results != null && $results[0]['totalRatings'] != null)
            {
              return $results[0]['totalRatings'];
            }
            
            return 0;
          }
        ## END PRIVATE METHODS
      }
    ?> \
    PHP:
    Now I think the problem is on the javascript:RateItem function inside the rating.class.php file above which call this function RateItem found at the top of the javascript file called rating.js below

    rating.js:


    Check the function RateItem right on top I really don't have any idea but I see the CSS class .rating but .rated is not found in any part of the script. I was wondering if that's the problem why is not refreshing the data to stage 1 to stage 3.

    This rating.js makes reference to ajax.rate.item.php file which is found inside the rating.js i will posted below in case it serves to the solution of this issue.

    ajax.rate.item.php
    <?php
      require_once("classes/include.all.php");
      
      // Check that the data was sent
      if (sizeof($_POST) == 0
        || $_POST['item'] == null
        || strlen(trim($_POST['item'])) == 0
        || $_POST['rating'] == null
        || strlen(trim($_POST['rating'])) == 0
        || $_POST['classes'] == null
        || strlen(trim($_POST['classes'])) == 0)
      {
        die("You shouldn't be attempting to access this file in this manner.");
      }
      
      echo Rating::RateItem($_POST['item'], $_POST['rating'], $_POST['classes']);
    ?>
    PHP:
    The file include.all.php in the ajax.rate.item.php calls the files error.class.php, database.class.php and the rating.class.php the first script on this post. it also define the database connection to the server and that's all there is

    <?php
      require_once("error.class.php");
      require_once("database.class.php");
      require_once("rating.class.php");
      Database::Initialize("mysql", "localhost", "3306", "menu", "root", "poliferico");
    ?>
    PHP:
    So the problem is in the connection from the rating.class.php to rating.js or inside the rating.js where there is not reference to the rated CSS class which define stage 3 in the illustration above. as I said it is suppose to go from stage 1 to stage 3 and define immediately instead with the rated css class instead of going from stage 1 to stage2 to stage 3

    there is another file used in this system and it is a javascript file call prototype.js and it seem to be a general file used by most java scripts to pull out functions from there.

    Prtotype.js
     
    co.ador, Jul 24, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    dunno, does not look like a very good script does it? :)

    first of all. why rely on the ajax output to populate the stars when the javascript already knows it?
    second - the way it's setup to use inline onclick events when you have prototype is not the best way - you can use a css selector to unify things. i am not a prototype user but if i had to do this in mootools, it would go like so:

    
    .vote {
       css define class
    }
    
    .one {
    
    }
    
    etc etc.
    
    
    <ul id="torpedo" class="stars">
    <li class="vote one" data-id="1"></li>
    <li class="vote two" data-id="2"></li>
    <li class="vote three" data-id="3"></li>
    <li class="vote four" data-id="4"></li>
    <li class="vote five" data-id="5"></li>
    </ul>
    
    ... and the js:
    
    window.addEvent("domready", function() {
        $$("ul.stars").each(function(el) {
             el.getElements("li.vote").addEvents({
                  click: function() {
                       var selectedRating = this.get("data-id"), parentId = el.get("id");
                       // call the ajax handler to register a vote for selectedRating and the id of the section.... then show it.
                  }
             });
        });
    
    });
    
    PHP:
    it's much more semantic. have a look here to see how i have done it in a real example:

    http://fragged.org/snippet-time-moorating-a-star-based-ajax-voting-script_422.html

    if you're stuck with prototype then fair enough though :) to gain any meaningful help you'd need to post a working url somewhere - i doubt anyone would be able to offer anything constructive by seeing just fragments.
     
    dimitar christoff, Jul 25, 2009 IP
  3. co.ador

    co.ador Peon

    Messages:
    120
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I will get you back on what you have done but first i would like to know how can I post my webpage on a server so it is on there and whenever i want to post something people can see it. Tell me the step to follow.

    somebody told me to get a server? get a ftp prgram load the files, and ?
     
    co.ador, Jul 25, 2009 IP
  4. co.ador

    co.ador Peon

    Messages:
    120
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Problem solved

    it was a simple / after the ?> causing all this trouble and headaches and it was fixed by SoulScratch at sitepoint forum

    If any body need the script for the RAting system just let PM
    Edit/Delete Message

    Though i like yours and I want to implemented as well Thank you very much
     
    co.ador, Jul 25, 2009 IP