Jump to content

class undefined probably caused by a AJAX functions


co.ador

Recommended Posts

Haku and moderator i will post here in AJAX help I hope this is not considered a double posting. I consider double posting in a same forum topic but if this is double posting let me know.

 

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>

 

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

 

stage1.gif

 

 

 

Stage 2

The user x clicked in one of the star in this Case Nike Air Jordan item was

stage2.gif

 

Stage 3

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

 

stage3u.gif

 

 

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
  }
?> \

 

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:

function RateItem(varItemId, varRating)

{

  var varOrigClassName = document.getElementById(varItemId).className;

 

  // Retrieve Ajax Feeds

  new Ajax.Request('ajax.rate.item.php',

    {

      method: 'post',

      parameters: {item: varItemId, rating: varRating, classes: varOrigClassName},

      onSuccess: ReloadRating,

      onFailure: RatingError

    }

  );

}

 

function ReadNameValuePairs(nameValuePair)

{

  var trimspaces = /(\s)+/;

  var returnData = new Array();

  var pairs      = nameValuePair.split('&');

 

  for (var i = 0; i < pairs.length; i++)

  {

    var pair = pairs.split('=');

    returnData[pair[0].replace(trimspaces, "")] = pair[1];

  }

 

  return returnData;

}

 

function ReloadRating(requestObj, jsonObj)

{

  var newlines  = /(\r\n|\r|\n)/;

  var returnData = ReadNameValuePairs(requestObj.responseText.replace(newlines, ""));

 

  document.getElementById(returnData['item']).className = returnData['classes'];

  var liObj = document.getElementById(returnData['item']).getElementsByTagName('a');

 

  for (var i = 0; i < liObj.length; i++)

  {

    liObj.onclick = function(){};

  }

}

 

function RatingError()

{

}

 

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']);
?>

 

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");
?>

 

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.