• [MOD] Rating by using AJAX functions-rating without reload (used by V@no) 5 0 5 1
Currently:  

Author Topic: [MOD] Rating by using AJAX functions-rating without reload (used by V@no)  (Read 57109 times)

0 Members and 1 Guest are viewing this topic.

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
Hello,

I've seen the rating form that uses V@no and looked a little bit for possibilities of sending DATA to a server without reloading the actual page. So I found AJAX - a combination of Javascript an XLM I think that makes these things possible.

So I found a simple script made with this that I want to present here:

http://www.konradin.net/hello.html

the hello.html sends information to the hello.php. The hello.php has the following code:

Code: [Select]
<?php
  $id 
$_REQUEST['id'];
  echo 
"rating||Thank you! You rated: $id";
?>


rating is the id of the DIV in that we see later "Thank you! You've rated:..."

So you see it is not difficult to work with to documents without reload.

The only thing I need now, is a rate.php that makes nothing else than process the image rate. And that's the step you could probably help me. Than I would write a mod that is really interesting I think becase it makes rating very comfortable and fast.

Thank you for helping,

Bye Konradin

Edit: @V@no: Is this the way you realized the rating on your page?
« Last Edit: June 13, 2007, 05:26:32 PM by mawenzi »

Offline V@no

  • If you don't tell me what to do, I won't tell you where you should go :)
  • Global Moderator
  • 4images Guru
  • *****
  • Posts: 17.849
  • mmm PHP...
    • View Profile
    • 4images MODs Demo
try this:
Code: [Select]
<?php
/**************************************************************************
 *                                                                        *
 *    4images - A Web Based Image Gallery Management System               *
 *    ----------------------------------------------------------------    *
 *                                                                        *
 *             File: rateimage.php                                        *
 *        Copyright: (C) 2002 Jan Sorgalla                                *
 *            Email: jan@4homepages.de                                    *
 *              Web: http://www.4homepages.de                             *
 *    Scriptversion: 1.7.2                                                *
 *                                                                        *
 *    Never released without support from: Nicky (http://www.nicky.net)   *
 *                                                                        *
 **************************************************************************
 *                                                                        *
 *    Dieses Script ist KEINE Freeware. Bitte lesen Sie die Lizenz-       *
 *    bedingungen (Lizenz.txt) f&#1100;r weitere Informationen.                 *
 *    ---------------------------------------------------------------     *
 *    This script is NOT freeware! Please read the Copyright Notice       *
 *    (Licence.txt) for further information.                              *
 *                                                                        *
 *************************************************************************/

$main_template '';
$nozip 1;
define('GET_CACHES'1);
define('ROOT_PATH''./');
include(
ROOT_PATH.'global.php');
require(
ROOT_PATH.'includes/sessions.php');
$user_access get_permission();
function 
update_image_rating_new($image_id$rating$image_row) {
  global 
$site_db;
  
$old_votes $image_row['image_votes'];
  
$old_rating $image_row['image_rating'];
  
$new_rating = (($old_rating $old_votes) + $rating) / ($old_votes 1);
  
$new_rating sprintf("%.2f"$new_rating);
  
$sql "UPDATE ".IMAGES_TABLE."
          SET image_votes = (
$old_votes + 1), image_rating = '$new_rating'
          WHERE image_id = 
$image_id";
  return 
$site_db->query($sql);
}
//-----------------------------------------------------
//--- Save Rating -------------------------------------
//-----------------------------------------------------
if ($action == "rateimage" && $id) {
  
$rating intval($HTTP_POST_VARS['rating']);
  
$cookie_name = (defined("COOKIE_NAME")) ? COOKIE_NAME "4images_";
  
$cookie_rated = isset($HTTP_COOKIE_VARS[$cookie_name.'rated']) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookie_name.'rated'])) : array();
  
$sql "SELECT cat_id, image_votes, image_rating
          FROM "
.IMAGES_TABLE."
          WHERE image_id = 
$id";
  
$image_row $site_db->query_firstrow($sql);
  if (
check_permission("auth_vote"$image_row['cat_id']))
  {

    if (
$rating && $rating <= MAX_RATING && $id) {
      if (!isset(
$session_info['rated_imgs'])) {
        
$session_info['rated_imgs'] = $site_sess->get_session_var("rated_imgs");
      }
      
$split_list = array();
      if (!empty(
$session_info['rated_imgs'])) {
        
$split_list explode(" "$session_info['rated_imgs']);
      }
      if (!
in_array($id$split_list) && !in_array($id$cookie_rated)) {
        if (
update_image_rating_new($id$rating$image_row))
        {
          
$session_info['rated_imgs'] .= " ".$id;
          
$session_info['rated_imgs'] = trim($session_info['rated_imgs']);
          
$site_sess->set_session_var("rated_imgs"$session_info['rated_imgs']);
          
$cookie_rated[] = $id;
          
$cookie_expire time() + 60 60 24 4;
          
setcookie($cookie_name.'rated'serialize($cookie_rated), $cookie_expireCOOKIE_PATHCOOKIE_DOMAINCOOKIE_SECURE);
          
$msg $lang['voting_success'];
        }
        else
        {
          
$msg $lang['voting_error'];
        }
      }
      else {
        
$msg $lang['already_voted'];
      }
    }
    else {
      
$msg $lang['voting_error'];
    }
  }
  else
  {
    
$msg $lang['no_permission'];
  }
}
else
{
  
$msg "Security violation";
}
die(
$msg);
?>
Your first three "must do" before you ask a question:
Please do not PM me asking for help unless you've been specifically asked to do so. Such PMs will be deleted without answer. (forum rule #6)
Extension for Firefox/Thunderbird: Master Password+    Back/Forward History Tweaks (restartless)    Cookies Manager+    Fit Images (restartless for Thunderbird)

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
Thank you Vano! I will try it.

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
What do I need to show after rating the new rating and the total number of votes? These strings are saved in a function ($new_rating, $old_votes + 1) and I can't use them outside the function. So, do I have to make a new db-query or is there a way to get function-variables?

Thank you, after than I would be done.

Bye, Konradin

Offline Stoleti

  • Hero Member
  • *****
  • Posts: 574
    • View Profile
and how added this on 4images  :?: (steps) ?

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
MOD - Rating without reload but changing dynamically the content
« Reply #5 on: May 09, 2006, 04:23:51 AM »
Mein erster Mod, My first Mod

EN: This Mod will make it possible to rate a picture without that the picture reloads.
DE: Durch diesen Mod können Bilder ohne reload bewertet werden.

DEMO: http://www.konradin.net/http://www.konradin.net/galerie/img879.htm
or something that makes the same but don't know if uses the same script ist the rating form on Vanos page.
auf Vanos Page wird glaube ich durch das gleiche Prinzip gehandelt, dort kann man sich also das Ergebnis ansehen.

STEP 1: Create a rating.php in your 4images folder with the following content (Please check Gurus!)

Code: [Select]
<?php
/**************************************************************************
 *                                                                        *
 *    4images - A Web Based Image Gallery Management System               *
 *    ----------------------------------------------------------------    *
 *                                                                        *
 *             File: rateimage.php                                        *
 *        Copyright: (C) 2002 Jan Sorgalla                                *
 *            Email: jan@4homepages.de                                    *
 *              Web: http://www.4homepages.de                             *
 *    Scriptversion: 1.7.2                                                *
 *                                                                        *
 *    Never released without support from: Nicky (http://www.nicky.net)   *
 *                                                                        *
 **************************************************************************
 *                                                                        *
 *    Dieses Script ist KEINE Freeware. Bitte lesen Sie die Lizenz-       *
 *    bedingungen (Lizenz.txt) f&#1100;r weitere Informationen.                 *
 *    ---------------------------------------------------------------     *
 *    This script is NOT freeware! Please read the Copyright Notice       *
 *    (Licence.txt) for further information.                              *
 *                                                                        *
 *************************************************************************/

$rating $_REQUEST['rating'];
$id $_REQUEST['id'];
$action "rateimage";

$main_template '';
$nozip 1;
define('GET_CACHES'1);
define('ROOT_PATH''./');
include(
ROOT_PATH.'global.php');
require(
ROOT_PATH.'includes/sessions.php');
$user_access get_permission();
function 
update_image_rating_new($image_id$rating$image_row, &$new_rating, &$old_votes) {
  global 
$site_db;
  
$old_votes $image_row['image_votes'];
  
$old_rating $image_row['image_rating'];
  
$new_rating = (($old_rating $old_votes) + $rating) / ($old_votes 1);
  
$new_rating sprintf("%.2f"$new_rating);
  
$sql "UPDATE ".IMAGES_TABLE."
          SET image_votes = (
$old_votes + 1), image_rating = '$new_rating'
          WHERE image_id = 
$image_id";
  return 
$site_db->query($sql);
}
//-----------------------------------------------------
//--- Save Rating -------------------------------------
//-----------------------------------------------------
if ($id) {
  
$rating intval($rating);
  
$cookie_name = (defined("COOKIE_NAME")) ? COOKIE_NAME "4images_";
  
$cookie_rated = isset($HTTP_COOKIE_VARS[$cookie_name.'rated']) ? unserialize(stripslashes($HTTP_COOKIE_VARS[$cookie_name.'rated'])) : array();
  
$sql "SELECT cat_id, image_votes, image_rating
          FROM "
.IMAGES_TABLE."
          WHERE image_id = 
$id";
  
$image_row $site_db->query_firstrow($sql);
  if (
check_permission("auth_vote"$image_row['cat_id']))
  {

    if (
$rating && $rating <= MAX_RATING && $id) {
      if (!isset(
$session_info['rated_imgs'])) {
        
$session_info['rated_imgs'] = $site_sess->get_session_var("rated_imgs");
      }
      
$split_list = array();
      if (!empty(
$session_info['rated_imgs'])) {
        
$split_list explode(" "$session_info['rated_imgs']);
      }
      if (!
in_array($id$split_list) && !in_array($id$cookie_rated)) {
        if (
update_image_rating_new($id$rating$image_row$new_rating$old_votes))
        {
          
$session_info['rated_imgs'] .= " ".$id;
          
$session_info['rated_imgs'] = trim($session_info['rated_imgs']);
          
$site_sess->set_session_var("rated_imgs"$session_info['rated_imgs']);
          
$cookie_rated[] = $id;
          
$cookie_expire time() + 60 60 24 4;
          
setcookie($cookie_name.'rated'serialize($cookie_rated), $cookie_expireCOOKIE_PATHCOOKIE_DOMAINCOOKIE_SECURE);
          
$msg $lang['voting_success'];
                  
$votes $old_votes 1;
  echo "kbdisplay||".$new_rating." (".$votes." ".$lang['votes'].")||";
        }
        else
        {
          
$msg $lang['voting_error'];
        }
      }
      else {
        
$msg $lang['already_voted'];
      }
    }
    else {
      
$msg $lang['voting_error'];
    }
  }
  else
  {
    
$msg $lang['no_permission'];
  }
}
else
{
  
$msg "Security violation";
}
die(
"kbrating||".$msg);
?>


STEP 2
Open rate_form.html and delete everything. After that insert the following:

Code: [Select]
<span id="kbrating">
<a href="javascript:rate('1');">Rate 1</a><br />
<a href="javascript:rate('2');">Rate 2</a><br />
<a href="javascript:rate('3');">Rate 3</a><br />
<a href="javascript:rate('4');">Rate 4</a><br />
<a href="javascript:rate('5');">Rate 5</a><br />
</span>

STEP 3
Open header.html of your templates and insert in the HEAD-Section the following Code:

Code: [Select]
<script type="text/javascript" language="Javascript">

function createXMLHttpRequest() {
  var ua;
  if(window.XMLHttpRequest) {
    try {
      ua = new XMLHttpRequest();
    } catch(e) {
      ua = false;
    }
  } else if(window.ActiveXObject) {
    try {
      ua = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      ua = false;
    }
  }
  return ua;
}
var req = createXMLHttpRequest();

function rate(id) {

  req.open('get', '{rating_url}&rating=' + id);
  req.onreadystatechange = handleResponse;
  req.send(null);
}

function handleResponse() {
  if(req.readyState <= 3){
    var text = '{lang_loading}';
var divid = 'kbrating';
      document.getElementById(divid).innerHTML = text;
   
  }
  if(req.readyState == 4){
    var response = req.responseText;
    var update = new Array();

    if(response.indexOf('||' != -1)) {
      update = response.split('||');
      document.getElementById(update[0]).innerHTML = update[1];
      document.getElementById(update[2]).innerHTML = update[3];

    }
  }
}
</script>



STEP 4

in details.html of your templates replace

Code: [Select]
{image_rating} ({image_votes} {lang_votes})
with

Code: [Select]
<span id="kbdisplay">{image_rating} ({image_votes} {lang_votes})</span>

STEP 5

open page_header.php in folder /includes/ and look for:

Code: [Select]
  "direction" => $lang['direction']
replace with:

Code: [Select]
  "direction" => $lang['direction'],
  "lang_loading" => $lang['loading']

add to your language files in your language:

Code: [Select]
$lang['loading'] = "wird geladen..."; or
Code: [Select]
$lang['loading'] = "loading...";

STEP 6

add anywhere in the details.php (or in the page_header.php if you want to use the rate form in other pages too) before the template-printout:

Code: [Select]
$site_template->register_vars("rating_url", ROOT_PATH."rating.php?id=".$image_id);
Done.

That should work - without support for rating scalas or Rating Stars but surely there`s somebody that helps me to integrate this too in a few seconds.

You can modify "Rate 1", "Rate 2", etc... with everything you want - stars, another text, etc.

Bye Konradin

Thx too Vano for piece of code

Edit 9. May, 23.50 -> radom.php to rating.php
-> Add {rating_url} registering to details.php
« Last Edit: May 10, 2006, 01:01:56 AM by konradin »

Offline V@no

  • If you don't tell me what to do, I won't tell you where you should go :)
  • Global Moderator
  • 4images Guru
  • *****
  • Posts: 17.849
  • mmm PHP...
    • View Profile
    • 4images MODs Demo
I see you got it ;)

two things though:
1) its not "random.php" but "rating.php" ;)
2) any links to 4images based files should be parsed by $site_sess->url() function, otherwise sessions can mess up.
So, instead of
Code: [Select]
  req.open('get', 'rating.php?rating=' + id + '&id={image_id}');use:
Code: [Select]
  req.open('get', '{rating_url}&rating=' + id);
And then in details.php register {rating_url} tag:
Code: [Select]
$site_template->register_vars("rating_url", ROOT_PATH."rating.php?id=".$image_id);
3) I see you added "echo" in the code, but it ment to load everything you want it to return, into $msg variable, which at the end of the script would output the result.

And then register {rating_url} tag in details.php:
Your first three "must do" before you ask a question:
Please do not PM me asking for help unless you've been specifically asked to do so. Such PMs will be deleted without answer. (forum rule #6)
Extension for Firefox/Thunderbird: Master Password+    Back/Forward History Tweaks (restartless)    Cookies Manager+    Fit Images (restartless for Thunderbird)

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net

3) I see you added "echo" in the code, but it ment to load everything you want it to return, into $msg variable, which at the end of the script would output the result.


I added another echo because this one updates the display of the actual/new total votes - And I want to update this only in case of success of the vote.

Thank you for helping me so much with the realisation of the MOd - Are you using the same feature on your site?

Do you have such a site like the rating.php for lightbox-adding, too? I'll try it myself, first.. I think that would be useful too, add lightbox-pictures fast.

Bye Konradin

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
Hello, I have a problem with the JavaScript:

I wanted to change it into:

Quote
function createXMLHttpRequest() {
  var ua;
  if(window.XMLHttpRequest) {
    try {
      ua = new XMLHttpRequest();
    } catch(e) {
      ua = false;
    }
  } else if(window.ActiveXObject) {
    try {
      ua = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      ua = false;
    }
  }
  return ua;
}
var req = createXMLHttpRequest();

function rate(id) {

  req.open('get', '{rating_url}&rating=' + id);
  req.onreadystatechange = handleResponse('kbrating');
  req.send(null);
}

function handleResponse(divid) {
  if(req.readyState <= 3){
    var text = '{lang_loading}';
    var divid = 'kbrating';
    document.getElementById(divid).innerHTML = text;
   
  }
  if(req.readyState == 4){
    var response = req.responseText;
    var update = new Array();

    if(response.indexOf('||' != -1)) {
      update = response.split('||');
      document.getElementById(update[0]).innerHTML = update[1];
      document.getElementById(update[2]).innerHTML = update[3];

    }
  }
}

But now the script only updates to "loading..." but not anymore after successful voting to "Thank you.." - but the vote works (after reload you can see it). What is the error of my JavaScript? I changed it for using the script with different divs (handleResponse(divid))

Thank You for helping, Bye Konradin

Offline impss

  • Sr. Member
  • ****
  • Posts: 382
    • View Profile
    • Cusstom.net
Did you get this to work ?


Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
Did you get this to work ?



What thing? The mod I mentiones above with Steps (rating without reloading) works perfectly. Now Lightbox-adding works perfectly too but I didn't public it yet. I found another solution for the javascript error I mentioned in my last topic.

Bye, Konradin

Offline V@no

  • If you don't tell me what to do, I won't tell you where you should go :)
  • Global Moderator
  • 4images Guru
  • *****
  • Posts: 17.849
  • mmm PHP...
    • View Profile
    • 4images MODs Demo
for the lightbox, there is already a mod exists, yet, it doesnt use any AJAX.
Your first three "must do" before you ask a question:
Please do not PM me asking for help unless you've been specifically asked to do so. Such PMs will be deleted without answer. (forum rule #6)
Extension for Firefox/Thunderbird: Master Password+    Back/Forward History Tweaks (restartless)    Cookies Manager+    Fit Images (restartless for Thunderbird)

Offline koikonut

  • Jr. Member
  • **
  • Posts: 75
    • View Profile
    • http://www.konradin.net
for the lightbox, there is already a mod exists, yet, it doesnt use any AJAX.

And what's its name?

Offline mawenzi

  • Moderator
  • 4images Guru
  • *****
  • Posts: 4.500
    • View Profile
Your first three "must do" before you ask a question ! ( © by V@no )
- please read the Forum Rules ...
- please study the FAQ ...
- please try to Search for your answer ...

You are on search for top 4images MOD's ?
- then please search here ... Mawenzi's Top 100+ MOD List (unsorted sorted) ...

Offline live@ct

  • Sr. Member
  • ****
  • Posts: 348
    • View Profile
I try this and its working, now a simple problem...

when you already voted, this display the msgs that says that you akready voted, but it display a java script error:

document.getElementByld(...) that its null  or itsnot and object

thanks for your help
Existen 10 tipos de personas, los que entienden el codigo binario y los que no.