How to implementing EasyPay Pakistan Payment gateway in WordPress? - javascript

Hi Everyone I am trying to implement the EasyPay Pakistan payment gateway for my website but i am getting this error Parameter Authentication failed my code is below which is in plugin they provided:
<?php
require '../../../wp-config.php';
$storeId = get_option('storeId');
$daysToExpire = get_option('daysToExpire');
$live = get_option('live');
$liveVal = $live['menu'];
$easypayIndexPage = '';
if ($liveVal == 'no') {
$easypayIndexPage = 'https://easypaystg.easypaisa.com.pk/easypay/Index.jsf';
} else {
$easypayIndexPage = 'https://easypay.easypaisa.com.pk/easypay/Index.jsf';
}
$merchantConfirmPage = home_url().'/wp-content/plugins/Easypay/confirmEasypay.php';
$options = get_option('autoRedirect');
//$autoRedirect = checked( isset( $options['autoRedirectCb'] ) );
$autoRedirect = checked( isset( $options['autoRedirectCb'] ),1,false );
if($autoRedirect) {
$autoRedirect = 1;
} else {
$autoRedirect = 0;
}
$orderId = $_GET['orderId'];
if (strpos($_GET['amount'], '.') !== false) {
$amount = $_GET['amount'];
} else {
$amount = sprintf("%0.1f",$_GET['amount']);
}
$custEmail = $_GET['custEmail'];
$custCell = $_GET['custCell'];
$hashKey = get_option('hashKey');
date_default_timezone_set('Asia/Karachi');
$expiryDate = '';
$currentDate = new DateTime();
if($daysToExpire != null) {
$currentDate->modify('+'.$daysToExpire.'day');
$expiryDate = $currentDate->format('Ymd His');
}
$paymentMethods = get_option('paymentMethod');
$paymentMethodVal = $paymentMethods['methods'];
$hashRequest = '';
if(strlen($hashKey) > 0 && (strlen($hashKey) == 16 || strlen($hashKey) == 24 || strlen($hashKey) == 32 )) {
// Create Parameter map
$paramMap = array();
$paramMap['amount'] = $amount ;
$paramMap['autoRedirect'] = $autoRedirect ;
if($custEmail != null && $custEmail != '') {
$paramMap['emailAddr'] = $custEmail ;
}
if($expiryDate != null && $expiryDate != '') {
$paramMap['expiryDate'] = $expiryDate;
}
if($custCell != null && $custCell != '') {
$paramMap['mobileNum'] = $custCell;
}
$paramMap['orderRefNum'] = $orderId ;
if($paymentMethodVal != null && $paymentMethodVal != '') {
$paramMap['paymentMethod'] = $paymentMethodVal ;
}
$paramMap['postBackURL'] = $merchantConfirmPage;
$paramMap['storeId'] = $storeId ;
//Creating string to be encoded
$mapString = '';
foreach ($paramMap as $key => $val) {
$mapString .= $key.'='.$val.'&';
}
$mapString = substr($mapString , 0, -1);
// Encrypting mapString
$ivlen = openssl_cipher_iv_length($cipher="AES-128-ECB");
$iv = openssl_random_pseudo_bytes($ivlen);
$crypttext = openssl_encrypt($mapString, $cipher, $hashKey,OPENSSL_RAW_DATA, $iv);
$hashRequest = base64_encode($crypttext);
}
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con) {
die('Could not connect: ' . mysqli_errno());
}
mysqli_select_db($con, DB_NAME);
global $wpdb;
$table_name = $wpdb->prefix . 'easypay_order';
// mysql inserting an order with pending status
$query = "INSERT INTO ".$table_name."( easypay_order_id, easypay_order_info, easypay_order_status, ipn_attr ) VALUES ('$orderId' ,'null', 'pending', 'null')";
try {
mysqli_query($con, $query);
} catch (Exception $ex) {
error_log($ex->getMessage());
}
// echo $easypayIndexPage;
//echo "\r\n".$storeId;
// echo $amount;
//echo $merchantConfirmPage;
//echo $orderId;
// echo $hashRequest;
//<?php header("Location: $easypayIndexPage") ?>
<form name="easypayform" method="post" action="<?php echo $easypayIndexPage; ?>">
<input name="storeId" value="<?php echo $storeId ?>" hidden = "true" readOnly="true" />
<input name="amount" value="<?php echo $amount ?>" hidden = "true"/>
<input name="postBackURL" value="<?php echo $merchantConfirmPage ?>" hidden = "true" readOnly="true" />
<input name="orderRefNum" value="<?php echo $orderId ?>" hidden = "true" readOnly="true" />
<?php if ($expiryDate != '' && $expiryDate != null) { ?>
<input name="expiryDate" value="<?php echo $expiryDate ?>" hidden = "false"/>
<?php } ?>
<input name="autoRedirect" value="<?php echo $autoRedirect ?>" hidden = "true"/>
<input name="emailAddr" value="<?php echo $custEmail ?>" hidden = "true"/>
<input name="mobileNum" value="<?php echo $custCell ?>" hidden = "true"/>
<input name="merchantHashedReq" value="<?php echo $hashRequest ?>" hidden = "true"/>
<input name="paymentMethod" value="<?php echo $paymentMethodVal ?>" hidden = "true"/>
</form>
<script data-cfasync="false" type="text/javascript">
document.easypayform.submit();
</script>
When I click on Proceed to easypay nothing appears on the page and just white black page appears, so after research I came to know that this below written code is not working:
<script data-cfasync="false" type="text/javascript">
document.easypayform.submit();
</script>
Therefore I added this line of code into my form so that I can manually click the button so redirect to EasyPay page.
<input type = "submit" value="Submit">
Now, when clicking on the submit button it is redirecting to EasyPay page but this error occurs saying Parameter Authentication failed.
So, is there anyone who can help me out in this implementation because there support team is not helpful.
I will be very thankful for your help.

This EasyPay plugin can't accept payment values greater than 2 decimals, so, by going in Woo-Commerce plugin in the currency's setting and changing number of decimals to 1 the EasyPay plugin issue will be resolve.

Related

Showing price on click input type="radio"?

[Product listing with clickable inputs][1]
i'm building a webshop system, and i would like to see on the product page that if a user selects a product size, the price will be displayed of the selected size..
Only the last displayed input works when i click on it.
Product listing with size inputs: https://i.stack.imgur.com/Wo6Oq.png
<?php
$count = 0;
foreach($original_array as $order_list){
$count++;
if($order_list['aantal'] == 0 || $order_list['aantal'] == ''){
$disableValue = 'disable';
}
if($count == 2){
$checked = 'checked=""';
}
?>
<div class="sc-item">
<input type="radio" name="variatie_maat[]" value="<?=$order_list['maat'];?>" onclick="myFunction();" id="<?=$order_list['maat'];?>-maat" <?=$disableValue;?> <?=$checked;?>>
<label for="<?=$order_list['maat'];?>-maat"><?=$order_list['maat'];?></label>
<input style="display:none;" value="<?=$order_list['prijs'];?>" id="prijs-<?=$order_list['prijs'];?>" name="variatie_prijs[]">
</div>
<?php
}
?>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("prijs-<?=$order_list['prijs'];?>").value;
document.getElementById(
"price").innerHTML = x;
}
</script>
'''
Try this.
<?php
$count = 0;
foreach($original_array as $order_list){
$count++;
if($order_list['aantal'] == 0 || $order_list['aantal'] == ''){
$disableValue = 'disable';
}
if($count == 2){
$checked = 'checked=""';
}
?>
<div class="sc-item">
<input type="radio" name="variatie_maat[]" value="<?=$order_list['maat'];?>" onclick="myFunction('<?=$order_list['prijs'];?>');" id="<?=$order_list['maat'];?>-maat" <?=$disableValue;?> <?=$checked;?>>
<label for="<?=$order_list['maat'];?>-maat"><?=$order_list['maat'];?></label>
<input style="display:none;" value="<?=$order_list['prijs'];?>" id="prijs-<?=$order_list['prijs'];?>" name="variatie_prijs[]">
</div>
<?php
}
?>
<script>
function myFunction(id) {
var x = document.getElementById("prijs-" + id).value;
document.getElementById("price").innerHTML = x;
}
</script>

Php variable if else statement

I am trying to define my php variable for my php poll vote. I want to echo "Have a good day!" if the vote in for "Hello" is more that "Others" else echo "Have a good night!". :
if ($votePercent < $votePercent) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
How to I define the variable $votePercent?
<div class="container">
<h3><?php echo $pollResult['poll']; ?></h3>
<p><b>Total Votes:</b> <?php echo $pollResult['total_votes']; ?></p>
<?php
if(!empty($pollResult['options'])){ $i=0;
//options bar color class array
$barColorArr = array('azure','emerald','violet','yellow','red');
//generate option bars with votes count
foreach($pollResult['options'] as $opt=>$vote){
//calculate vote percent
$votePercent = round(($vote/$pollResult['total_votes'])*100);
$votePercent = !empty($votePercent)?$votePercent.'%':'0%';
//define bar color class
if(!array_key_exists($i, $barColorArr)){
$i = 0;
}
$barColor = $barColorArr[$i];
?>
<div class="bar-main-container <?php echo $barColor; ?>">
<div class="txt"><?php echo $opt; ?></div>
<div class="wrap">
<div class="bar-percentage"><?php echo $votePercent; ?></div>
<div class="bar-container">
<div class="bar" style="width: <?php echo $votePercent; ?>;"></div>
</div>
</div>
</div>
<?php $i++; } } ?>
Back To Poll
</div>
This is the how I am connected to mysql.
<?php
class Poll{
private $dbHost = 'localhost';
private $dbUser = '';
private $dbPwd = '';
private $dbName = '';
private $db = false;
private $pollTbl = 'polls';
private $optTbl = 'poll_options';
private $voteTbl = 'poll_votes';
public function __construct(){
if(!$this->db){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUser, $this->dbPwd, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Runs query to the database
* #param string SQL
* #param string count, single, all
*/
private function getQuery($sql,$returnType = ''){
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
}
return !empty($data)?$data:false;
}
/*
* Get polls data
* Returns single or multiple poll data with respective options
* #param string single, all
*/
public function getPolls($pollType = 'single'){
$pollData = array();
$sql = "SELECT * FROM ".$this->pollTbl." WHERE status = '1' ORDER BY created DESC";
$pollResult = $this->getQuery($sql, $pollType);
if(!empty($pollResult)){
if($pollType == 'single'){
$pollData['poll'] = $pollResult;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$pollResult['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData['options'] = $optionResult;
}else{
$i = 0;
foreach($pollResult as $prow){
$pollData[$i]['poll'] = $prow;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$prow['id']." AND status = '1'";
$optionResult = $this->getQuery($sql2);
$pollData[$i]['options'] = $optionResult;
}
}
}
return !empty($pollData)?$pollData:false;
}
/*
* Submit vote
* #param array of poll option data
*/
public function vote($data = array()){
if(!isset($data['poll_id']) || !isset($data['poll_option_id']) || isset($_COOKIE[$data['poll_id']])){
return false;
}else{
$sql = "SELECT * FROM ".$this->voteTbl." WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$preVote = $this->getQuery($sql, 'count');
if($preVote > 0){
$query = "UPDATE ".$this->voteTbl." SET vote_count = vote_count+1 WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$update = $this->db->query($query);
}else{
$query = "INSERT INTO ".$this->voteTbl." (poll_id,poll_option_id,vote_count) VALUES (".$data['poll_id'].",".$data['poll_option_id'].",1)";
$insert = $this->db->query($query);
}
return true;
}
}
/*
* Get poll result
* #param poll ID
*/
public function getResult($pollID){
$resultData = array();
if(!empty($pollID)){
$sql = "SELECT p.subject, SUM(v.vote_count) as total_votes FROM ".$this->voteTbl." as v LEFT JOIN ".$this->pollTbl." as p ON p.id = v.poll_id WHERE poll_id = ".$pollID;
$pollResult = $this->getQuery($sql,'single');
if(!empty($pollResult)){
$resultData['poll'] = $pollResult['subject'];
$resultData['total_votes'] = $pollResult['total_votes'];
$sql2 = "SELECT o.id, o.name, v.vote_count FROM ".$this->optTbl." as o LEFT JOIN ".$this->voteTbl." as v ON v.poll_option_id = o.id WHERE o.poll_id = ".$pollID;
$optResult = $this->getQuery($sql2);
if(!empty($optResult)){
foreach($optResult as $orow){
$resultData['options'][$orow['name']] = $orow['vote_count'];
}
}
}
}
return !empty($resultData)?$resultData:false;
}
}
This is the index.php code.
<form method="post" action="">
<h3><?php echo $pollData['poll']['subject']; ?></h3>
<ul>
<?php foreach($pollData['options'] as $opt){
echo '<li><input type="radio" name="voteOpt" value="'.$opt['id'].'" >'.$opt['name'].'</li>';
} ?>
</ul>
<input type="hidden" name="pollID" value="<?php echo $pollData['poll']['id']; ?>">
<input type="submit" name="voteSubmit" value="Vote">
Results
</form>
This is my test url: php poll. Please let me know if you need more details. I am not sure which code is needed to be shown here. Thankyou so much for helping.
Try this --
results.php
if ($_GET['PollID'] == 2) {
$votePercent = "Have a good day!";
} else {
$votePercent = "Have a good night!";
}
index.php
In this page, radio button value are 1 and 2

Add Active Link Class

I have a dynamic navigation bar that stores the pages/URLs in a database. The nav.php is the script that handles displaying and running through the SQL queries to display the links. I'm having a difficult time adding a script that adds an active class to the links.
My page URLs are as follows:
/page/2/full-service-fleet
/rate-request
/employment
/page/5/links
/page/6/contact
PHP:
<nav>
<?php
while ($row = $result->fetch_assoc())
{
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != ''){
$navlink = $navurl;
}
else{
$navlink = "page.php?id=".$navid."&title=".$navslug;
}
if (substr($navlink,0,4) != "http"){
if ($server_name <> "") {
$navlink = "http://".$server_name."/".$navlink;
}
}
if ($navurl == '#'){
$navlink = $navurl;
}
if ($navnum ==0){
?>
<?php echo $navname; ?>
<?php
}else{
?>
<!-- the rest isn't necessary -->
......
</nav>
Browser Rendered Output
The actual links that are being displayed is this line:
<?php echo $navname; ?>
JS Script:
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}
var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});
You can use this code as it is or you can grab some idea from this one
:
<div class="w3-top" style="z-index: 999;">
<div class="navcontainer">
<div class="w3-hide-small">
<img src="/images/-logo.png" alt="U.S. Transportation" title="" style="">
<div class="abovenav w3-right">
<button class="w3-button w3-round-large" onclick="">Customer Login</button>
<button class="w3-button w3-round-large" onclick="">Carrier Login</button>
</div>
</div>
<div class="w3-bar nav w3-card-2 w3-left-align w3-large" style="text-overflow: auto;" id="nav">
<div class="w3-hide-large w3-hide-medium">
<a class="w3-hide-medium w3-hide-large w3-right w3-margin-right w3-text-white buttons" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><span class="fa fa-bars"></span></a>
<a href="<?php
if ($server_name <> "") {
echo "http://" . $server_name . "/";
}
?>/index.php" title="Home" class="w3-left w3-margin-left w3-text-white buttons"><span class="fa fa-home w3-xlarge"></span></a>
</div>
<div style="margin-right: 10%;">
<nav>
<?php
include 'yortal\db.php';
$sql = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = 0 and status = 'ON' order by sort DESC";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != '') {
$navlink = $navurl;
} else {
$navlink = "page.php?id=" . $navid . "&title=" . $navslug;
}
if (substr($navlink, 0, 4) != "http") {
if ($server_name <> "") {
$navlink = "http://" . $server_name . "/" . $navlink;
}
}
if ($navurl == '#') {
$navlink = $navurl;
}
if ($navnum == 0) {
$current_link = $_SERVER[REQUEST_URI];
$active_class = ($navlink==$current_link)?'active':'';
?>
<?php echo $navname; ?>
<?php
} else {
?>
<div class="w3-dropdown-hover w3-hide-small w3-right" onclick="javascript:window.location.href = '<?php echo $navlink; ?>'">
<button class="w3-button"><?php echo $navname; ?></button>
<div class="w3-dropdown-content w3-white w3-card-4">
<?php
//Subpages
$sql2 = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = " . $navid . " and status = 'ON' order by sort";
$result2 = $mysqli->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$dropid = $row2['id'];
$dropname = $row2['nav'];
$dropurl = $row2['url'];
$dropslug = $row2['slug'];
$dropnum = $row2['num'];
if ($dropurl != '') {
$droplink = $dropurl;
} else {
$droplink = "page.php?id=" . $dropid . "&title=" . $dropslug;
}
if (substr($droplink, 0, 4) != "http") {
if ($server_name <> "") {
$droplink = "http://" . $server_name . "/" . $droplink;
}
}
if ($dropurl == '#') {
$droplink = $dropurl;
}
?>
<?php
$actual_link = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
$active_class = ($actual_link==$droplink || $_SERVER[REQUEST_URI] == $droplink)?'active':'';
?>
<?php echo $dropname; ?>
<?php
}
?>
</div>
</div><?php
}
}
?>
</nav>
</div>
</div>
</div>
First of all I'm pretty sure that you may have got wrong path. I suggest the following implementation which will depend on each():
$(document).ready(function(){
loc = window.location.pathname;
$("nav a").each(function(){
if ($(this).attr("href") == loc){
$(this).addClass("active");
$(this).attr("href") = "#"; // to prevent link to the same page
return true;
}
});
});

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

Opencart customization: server-side script for rating

I've added a custom table into the Opencart database, where I have a field/column, called average_rating (value = null to 5).
In my (custom) template (.tpl file) I've added a code to get and show the rating of current record from database.
Here is the code within .tpl file:
<div class="form-group">
<label class="col-sm-2 control-label" for="input-average_rating"><?php echo $entry_average_rating; ?></label>
<div class="col-sm-10">
<input type="hidden" name="average_rating" value="<?php echo $average_rating; ?>" id="input-average_rating" />
<?php for ($i = 0; $i < $average_rating; $i++) { ?>
<div class="rating_hover" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip"><i class="fa fa-star"></i></div>
<?php } ?>
<?php for ($i = $average_rating; $i <= 4; $i++) { ?>
<div class="rating_normal" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip"><i class="fa fa-star"></i></div>
<?php } ?>
</div>
</div>
For the blue-stars, I use .rating_hover class, for the grey-ones: .rating_normal class (see the picture below).
All this stuff works fine. But now I want to do something I have no experience with and I would appreciate any tip concerning my question.
Question: When a mouse pointer is over a grey star, it must become blue, like the ones before it. And when clicked on a star, my hidden input must get the value of title attribute of the clicked div-element. I wouldn't like to write a client-side Javascript to do this. Could somebody give a tip on how to do this with JSON or AJAX... or somehow please?
I mean: something like this:
$('div[id=\'r*\']').onmouseover({
// for (i=$average_rating; i<=[current_id]; i++) {
// ??? document.getElementById('r[i]').style.ClassName = 'someclass';
});
Javascript-alternative works fine, but I still have problems with JSON-script:
This is how javascript works:
Inside every div-element I added following commands:
<div ... onclick="rOnClick(<?php echo ($i+1) ?>);" onmouseover="rOnMouseOver(<?php echo ($i+1) ?>);" onmouseout="rOnMouseOut(<?php echo ($i+1) ?>);" ... >
And my Javascript functions are now, as follows:
<script type="text/javascript">
function rOnMouseOver(id) {
var ar = parseInt(document.getElementById('input-average_rating').value);
if (isNaN(ar)) {
ar = 0;
}
for(i = (ar+1); i <= id; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
}
function rOnMouseOut(id) {
var ar = parseInt(document.getElementById('input-average_rating').value);
if (isNaN(ar)) {
ar = 0;
}
for(i = 1; i <= ar; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
for(i = (ar+1); i <= id; i++) {
document.getElementById('r' + i).className = 'rating_normal';
}
}
function rOnClick(id) {
document.getElementById('input-average_rating').value = id;
for(i = 1; i <= id; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
for(i = (id+1); i <= 5; i++) {
document.getElementById('r' + i).className = 'rating_normal';
}
}
</script>
Please add another css class 'rating' in all rating divs. Also you will be needed to add a different class 'rated' for existing/clicked rated value. Then add following script:
$('.rating').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('rating_over');
$(this).nextAll().removeClass('rating_normal');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
$('.rated').addClass('ratings_over'); // back to rated one
}
);
$('.rating').bind('click', function() {
$('.rating').removeClass('rated');
$(this).addClass('rated');
$('#input-average_rating').val($(this).attr('title'));
});

Categories

Resources