Reload or Refresh Page after comment successfully submitted in Ajax - php
I am trying to reload the page after the comment is successfully submitted
Comment submitted through Ajax
After this line
// Save the comment
$state = $comment->store();
If i am trying to use location.reload(); as
// Save the comment
$state = $comment->store();
location.reload();
then its not working and comment not even submitting
Below is complete code
Can any one help - how to refresh and load page when comment is successfully submitted and stored in backend
<?php
defined('_JEXEC') or die('Unauthorized Access');
require_once(JPATH_COMPONENT . '/views/views.php');
class EasyBlogViewComments extends EasyBlogView
{
/**
* Processes comment saving
*
* #since 4.0
* #access public
* #param string
* #return
*/
public function save()
{
// Check for request forgeries
EB::checkToken();
// Test if user is really allowed to post comments
if (!$this->acl->get('allow_comment')) {
return $ajax->reject(JText::_('COM_EASYBLOG_NO_PERMISSION_TO_POST_COMMENT'));
}
// Default values
$moderated = false;
$parentId = $this->input->get('parentId', 0, 'int');
$depth = $this->input->get('depth', 0, 'int');
$subscribe = $this->input->get('subscribe', false, 'bool');
$email = $this->input->get('email', '', 'email');
$message = $this->input->get('comment', '', 'default');
$name = $this->input->get('name', '', 'default');
$username = $this->input->get('username', '', 'default');
$password = $this->input->get('password', '', 'default');
$title = $this->input->get('title', '', 'default');
$terms = $this->input->get('terms', false, 'bool');
$blogId = $this->input->get('blogId', 0, 'int');
$isCB = $this->input->get('iscb', 0, 'int');
// If there is no name, and the current user is logged in, use their name instead
if (!$name && $this->my->id) {
$user = EB::user($this->my->id);
$name = $user->getName();
}
// Validate the email
$data = array('post_id' => $blogId, 'comment' => $message, 'title' => $title, 'email' => $email, 'name' => $name, 'username' => $username, 'terms' => $terms);
// Load up comment table
$comment = EB::table('Comment');
$state = $comment->validatePost($data);
if (!$state) {
return $this->ajax->reject($comment->getError());
}
// Bind the data on the comment table now
$comment->bindPost($data);
// Check for spams
if ($comment->isSpam()) {
return $this->ajax->reject(JText::_('COM_EASYBLOG_SPAM_DETECTED_IN_COMMENT'));
}
$captchaResponse = EB::captcha()->verify();
// Perform captcha verification
if (isset($captchaResponse->success) && $captchaResponse->success == false) {
return $this->ajax->reject($captchaResponse->errorCodes);
}
// Get current date
$date = EB::date();
// Set other attributes for the comment
$comment->created = $date->toSql();
$comment->modified = $date->toSql();
$comment->published = true;
$comment->parent_id = $parentId;
$comment->created_by = $this->my->id;
// Process user registrations via comment
$register = $this->input->get('register', '', 'bool');
if ($register && $this->my->guest) {
if (empty($password) || empty($username) || empty($email)) {
return $this->ajax->reject('COM_EASYBLOG_COMMENT_REGISTRATION_FIELD_EMPTY');
}
$userModel = EB::model('Users');
$id = $userModel->createUser($username, $email, $name, $password);
if (!is_numeric($id)) {
return $this->ajax->reject($id);
}
$comment->created_by = $id;
}
$totalComments = $this->input->get('totalComment', 0, 'int');
// Determines if comment moderation is enabled
if ($this->config->get('comment_moderatecomment') == 1 || ($this->my->guest && $this->config->get('comment_moderateguestcomment'))) {
$comment->published = EBLOG_COMMENT_STATUS_MODERATED;
}
// Load up the blog table
$blog = EB::table('Blog');
$blog->load($comment->post_id);
// If moderation for author is disabled, ensure that the comment is also published automatically.
if ((!$this->config->get('comment_moderateauthorcomment') && $blog->created_by == $this->my->id) || EB::isSiteAdmin()) {
$comment->published = true;
}
// Update the ordering of the comment before storing
$comment->updateOrdering();
// Save the comment
$state = $comment->store();
if (!$state) {
return $this->ajax->reject($comment->getError());
}
$resultMessage = JText::_('COM_EASYBLOG_COMMENTS_POSTED_SUCCESS');
$resultState = 'success';
// If user registered as well, display a proper message
if ($register) {
$resultMessage = JText::_('COM_EASYBLOG_COMMENTS_SUCCESS_AND_REGISTERED');
}
if ($comment->isModerated()) {
$resultMessage = JText::_('COM_EASYBLOG_COMMENT_POSTED_UNDER_MODERATION');
$resultState = 'info';
}
// Process comment subscription
if ($subscribe && $this->config->get('main_subscription') && $blog->subscription) {
$subscribeModel = EB::model('Subscription');
$subscribeModel->subscribe('blog', $blog->id, $email, $name, $this->my->id);
}
// Process comment notifications
$comment->processEmails($comment->isModerated(), $blog);
// Set the comment depth
$comment->depth = $this->input->get('depth', 0, 'int');
// Update the sent flag
$comment->updateSent();
// Format the comments
$result = EB::comment()->format(array($comment));
$comment = $result[0];
$language = JFactory::getLanguage();
$rtl = $language->isRTL();
$theme = EB::template();
$theme->set('comment', $comment);
$theme->set('rtl', $rtl);
$output = '';
if ($isCB) {
// if the is saving from CB plugin, then we need to display the output using different template.
$output = $theme->output('site/comments/cb.item');
} else {
$output = $theme->output('site/comments/default.item');
}
return $this->ajax->resolve($output, $resultMessage, $resultState);
}
public function reloadCaptcha()
{
$ajax = EB::ajax();
// Get the previous captcha id.
$id = $this->input->get('previousId', 0, 'int');
$captcha = EB::table('Captcha');
$state = $captcha->load($id);
if ($state) {
$captcha->delete();
}
// Generate a new captcha
$captcha = EB::table('Captcha');
$captcha->created = EB::date()->toSql();
$captcha->store();
$image = EB::_('index.php?option=com_easyblog&task=captcha.generate&tmpl=component&no_html=1&id=' . $captcha->id, false);
return $ajax->resolve($image, $captcha->id);
}
2nd File
EasyBlog.module('comments/form', function($) {
var module = this;
EasyBlog.require()
.script('comments/captcha', 'comments/list')
.library('markitup')
.done(function($) {
EasyBlog.Controller('Comments.Form', {
defaultOptions: {
"{formWrapper}": "[data-comment-form-wrapper]",
"{form}": "[data-comment-form]",
"{title}": "[data-comment-title]",
"{name}": "[data-comment-name]",
"{username}": "[data-comment-username]",
"{password}": "[data-comment-password]",
"{email}": "[data-comment-email]",
"{register}": "[data-comment-register]",
"{website}": "[data-comment-website]",
"{counter}": "[data-comment-counter]",
"{subscribe}" : "[data-comment-subscribe]",
"{terms}": "[data-comment-terms]",
"{tncLink}": "[data-comment-tnc]",
"{parentId}" : "[data-comment-parent-id]",
"{commentDepth}": "[data-comment-depth]",
"{blogId}" : "[data-comment-blog-id]",
"{depth}": "[data-comment-depth]",
"{notice}": "[data-comment-notice]",
"{editor}": "[data-comment-editor]",
"{submit}": "[data-comment-submit]",
"{formToken}": "[data-comment-token]",
"{recaptcha}": "[data-recaptcha-item]"
}
}, function(self, opts, base) {
return {
init: function() {
self.initEditor();
self.list = self.addPlugin('list');
// If recaptcha is enabled, we should skip the normal captcha
var recaptcha = self.recaptcha.inside(self.element).length;
if (recaptcha < 1) {
self.captcha = self.addPlugin('captcha');
}
},
initEditor: function() {
if (self.editor().data('comment-bbcode') == 1) {
self.editor().markItUp(window.EasyBlogBBCodeSettings);
}
},
setNotice: function(message, type) {
var className = '';
if (type == 'error') {
className = 'alert-danger';
}
if (type == 'success') {
className = 'alert-success';
}
if (type == 'info') {
className = 'alert-info';
}
self.notice()
.removeClass('hide')
.addClass('alert ' + className)
.html(message);
},
resetForm: function() {
// If the comment form has a parent id, we need to reposition the comment form back.
var parentId = self.parentId().val();
if (parentId != 0) {
self.form().appendTo(self.formWrapper());
}
// Reset the form
self.username().val('');
self.password().val('');
self.subscribe().attr('checked', false);
self.editor().val('');
self.website().val('');
self.name().val('');
self.depth().val(0);
self.parentId().val(0);
self.trigger('resetForm');
// Determine if recaptcha is available
var recaptcha = self.recaptcha.inside(self.element);
// Get recaptcha's response
if (recaptcha.length > 0) {
grecaptcha.reset();
}
},
resetNotice: function() {
self.notice()
.removeClass('info error')
.html('');
},
"{self} replyComment": function(el, event, commentItem, commentId, commentDepth) {
// Hide notices in the reply form
self.notice().addClass('hide');
// When user tries to reply to an existing comment, move the form next to the level of the comment item
commentItem.after(self.form());
self.depth().val(commentDepth);
// Set the new parent id to the comment's id
self.parentId().val(commentId);
},
"{self} cancelReply": function(el, event, commentItem, commentId) {
// Set the parent id to 0
self.parentId().val(0);
// Reset the comment depth back to 0
self.depth().val(0);
// Relocate the form back to it's origin
self.formWrapper().html(self.form());
},
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
},
getValues: function() {
var data = {
title: self.title().val(),
name: self.name().val(),
email: self.email().val(),
username: self.username().val(),
password: self.password().val(),
website: self.website().val(),
subscribe: self.subscribe().is(':checked') ? 1 : 0,
register: self.register().is(':checked') ? 1 : 0,
comment: self.editor().val(),
terms: self.terms().is(':checked') ? 1 : 0,
depth: self.depth().val(),
parentId: self.parentId().val(),
blogId: self.blogId().val()
};
// token
// data[self.formToken().attr('name')] = 1;
// Determine if recaptcha is available
var recaptcha = self.recaptcha.inside(self.element);
// Get recaptcha's response
if (recaptcha.length > 0) {
data.recaptcha = grecaptcha.getResponse();
}
self.trigger('submitComment', [data]);
return data;
},
"{tncLink} click": function() {
EasyBlog.dialog({
content: EasyBlog.ajax('site/views/comments/terms')
})
},
"{submit} click" : function(el, event) {
event.preventDefault();
// Reset notices
self.resetNotice();
// Add loading indicator on the button
$(el).attr('disabled', true);
var tmp = $(el).html();
$(el).html('<i class="fa fa-repeat fa-spin"></i>');
// Get the form values
var data = self.getValues();
// Perform an ajax call to submit the comment
EasyBlog.ajax('site/views/comments/save', data)
.done(function(output, message, state) {
self.setNotice(message, state);
self.trigger('commentAdded',[output, data]);
})
.fail(function(message) {
self.setNotice(message, 'error');
})
.always(function(){
$(el).removeAttr('disabled');
$(el).html(tmp);
self.trigger('reloadCaptcha');
});
return false;
}
}
});
module.resolve();
});
});
I would hazard a guess that the place to add the location.reload() would be within this snippet:
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
},
So perhaps like:
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
/* reload */
location.reload();
},
Or, you could add it to the .done method within EasyBlog.ajax .... pretty much the same thing I think by looking at the code though
Related
Yii2 login by otp does not make a cookie
I use Yii2-advanced-app(2.0.15) and i need to do the logon operation with OTP. With the cell number and password, everything is correct and the cookie is correct but when I use an opt, no value is created for the cookie. My ajax code: $("#m-sendCode__form-submit").click(function() { $(this).attr('disabled','true'); let mobile = $('#mobile').val(); let csrfToken = $('meta[name="csrf-token"]').attr("content"); let rememberMe = $("#remember2").prop('checked'); // console.log(rememberMe); $.ajax({ url: '/loginbysms', method: 'POST', data: { _csrfFrontend: csrfToken, phone: phone, rememberMe: rememberMe }, timeout: 6000 }) .done(function(data) { let response = JSON.parse(data); // console.log(data); if (response.sent === 1){ $.ajax({ url: '/loginbysms', method: 'POST', data: { _csrfFrontend: csrfToken, verify: verify, // rememberMe: rememberMe }, }) .done(function(data) { let s = JSON.parse(data); if (s.status === 1){ window.location.href = '/'; } }); } }) .fail(function(error)){ console.log(error); }); }); And my controller is: public function actionLoginbysms() { $dataAjax = Yii::$app->request->post(); $session = Yii::$app->session; if(isset($dataAjax)) { if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) { $phone = $dataAjax['phone']; $user = User::findByPhone2($phone); $sendSMS = new SendSMS(); if ($sendSMS->SendSMS($user->user_otp, $phone)) { echo json_encode(['sent' => 1]); exit; } else { echo json_encode(['sent' => 0]); exit; } } if(isset($dataAjax['verify]) && !empty($dataAjax['verfy'])){ $authorizedUser = User::findByOtp($session- >get('user_phone'), $dataAjax['verify']); if (isset($authorizedUser) && !empty($authorizedUser)) { Yii::$app->user->login($authorizedUser, 3600 * 24 * 30) echo json_encode(['status' => 1]); exit; } } } } When everything is true and the code is sent correctly by the user, the user enters the home page correctly but no value for the cookie is saved. Please tell me the mistake.
The controller should be changed as follows: public function actionLoginbysms() { $dataAjax = Yii::$app->request->post(); $session = Yii::$app->session; if(Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) { $mobile = $dataAjax['phone']; $user = User::findByPhone2($phone); if ($user) { unset($dataAjax['phone']); $numbers = range(10000, 99999); shuffle($numbers); $session->set('user_phone', $phone); if (isset($dataAjax['rememberMe']) && !empty($dataAjax['rememberMe']) && ($dataAjax['rememberMe'] == true)) { $session->set('rememberMe', 'yes'); unset($dataAjax['rememberMe']); } $user->user_otp = $numbers[0]; $user->save(); try { $sendSMS = new SendSMS(); $sendSMS->SendSMS($user->user_otp, $phone); } catch (\Throwable $e) { return [ 'sent' => 0 ]; } return [ 'sent' => 1 ]; } else { return ['user_not_found' => 1]; } } else if (isset($dataAjax['verify']) && !empty($dataAjax['verify'])) { if ($session->isActive && $session->has('user_phone')) { $authorizedUser = User::findByOtp($session->get('user_phone'), $dataAjax['verify']); if (isset($authorizedUser) && !empty($authorizedUser)) { unset($dataAjax['verify']); $session->remove('user_phone'); $authorizedUser->user_otp = ''; $authorizedUser->save(); if(Yii::$app->user->login($authorizedUser, 3600 * 24 * 30)) { return ['authenticationSuccess' => 1]; } } } return ['authenticationSuccess' => 0]; } } } As #rob006 said, we should not use exit. With the help of Yii::#app->response->format = Response::FORMAT_JSON, everything works fine
Ajax response from Zend frameword
Recently, I've been trying to create an online CRM using jquery/php/xml-rpc and I've had an issue that I just can't seem to find the solution to. I currently have an ajax request sending an element id to a php document that when opened on its own (as a direct url to the document) returns a response from the API server (either a Boolean or some error like 'wrong data'). However this doesn't come out to my page at all and I am not sure the data I am sending is even getting through to the php document. This is my jquery code: $('#SomeElement').on('click', function(){ var id = $('#ELEMENTID').attr('value'); $.ajax ({ type:'POST', url: 'PHPfile.php', dataType: 'json', data: {id:id}, success: function(data) { if(data.indexOf('YES') === -1){ $('.alert-success').show(); $('.alert-success').html(data); /*setTimeout(function() { $('.alert-success').fadeOut('slow'); location.reload(); }, 2000);*/ } else { $('.alert-danger').show(); $('.alert-danger').html(data); /*setTimeout(function() { $('.alert-danger').fadeOut('slow'); location.reload(); }, 2000);*/ } } }); }); And this is my PHP code: require 'init_autoloader.php'; Zend\Mvc\Application::init(require 'config/application.config.php')->run(); $q = mysqli_query($conn, "SELECT * FROM some db WHERE somekey = '$_POST[id]'"); $main = mysqli_fetch_assoc($q); if($main['someentry'] !== '0') { echo 'This is FALSE'; } else { $r = mysqli_query($conn, "SELECT * FROM side_db WHERE side_id = '$_POST[id]'"); $p = mysqli_query($conn, "SELECT * FROM ext_db WHERE ext_id = '$_POST[id]'"); $m = mysqli_query($conn, "SELECT * FROM img_db WHERE img_id = '$_POST[id]'"); $side = mysqli_fetch_assoc($r); $ext = mysqli_fetch_assoc($p); if((int)$ext['gt'] === '0' || (int)$ext['gt'] === '1') { $g = 'yes'; } else { $g = 'no'; } foreach($ext as $key => $value) { if($key === 'somestring') { continue; }else if($value === '0' || $value === '1') { $ext[$key] = 'no'; } else if($value === '2'){ $ext[$key] = 'yes'; } } foreach($main as $k => $v) { if($v === '0' || $v === '1') { $main[$k] = 'no'; } else if($v === '2'){ $main[$k] = 'yes'; } } require 'init_autoloader.php'; Zend\Mvc\Application::init(require 'config/application.config.php')->run(); $appkey = 'appkey'; $someid = id; $something = 'something'; $else = 'else'; $divarray = Array ( 'HEAL' = Array( [0] = "WARLOCK", [1] = "PRIEST", [2] = "ROGUE", [3] = "WARRIOR", [4] = "MAGE" ), "someENTRY" = 'YES' ); $oxClient = new \Zend\XmlRpc\Client('http://link-to-server.php'); $somenewrequest = $oxClient->call('class.OfAPI',array($appkey,$someid,$something,$else,$divarray)); $res = $oxClient->getLastResponse(); echo $res; $client = new \Zend\XmlRpc\Client('http://link-to-server.php'); if($m !== FALSE) { $j = 1; while($img = mysqli_fetch_assoc($m)) { $pather = str_replace('../',"",$img['img_path']); $url = str_replace('www.', "", $_SERVER['HTTP_HOST']); $imagedata = file_get_contents('OUR/FILE/PATH/OF/SERVER'.$url.'/'.$pather); $base64 = base64_encode($imagedata); $SOMEID = $res; $image = $base64; $client->call('CLASS.IMAGESOMETHING',array($appkey,$usr,$psw,$res,$image)); $j++; } } $fin = mysqli_query($conn, "UPDATE our_db SET avalue = '1' WHERE somefield = '$_POST[id]'"); echo 'You succeeded in doing w/e'; } Excluding all the small errors I might have done due to having to rewrite half of the code to protect sensitive information, I want to know what I can change so that I can see the responses pop up on the page where the ajax is run. I tried JSON.encode on the $res but that didn't seem to solve anything. Is there something I am missing or something I can do differently to get the responses I need or even see if the ajax variable is getting through to the php document. Either way I would be happy to know what I am doing wrong so I can improve and not have to run into the problem in the future. Thanks in advance!
In your $.(ajax) please put id in quotes to make sure it is interpreted as field name: data: {'id':id}, Use developer-tools of google chrome to inspect your POST-request going to the server. Here a very good intro: https://blog.versionone.com/spy-on-browser-http-requests/
How to get supplier id when it has just been added in the db?
When I add a supplier in the admin panel (and click the save button) I want to retrieve its ID in the method postProcess() in the controller prestashop/controllers/admin/AdminSuppliersController.php in such a way that I can associate to this supplier other custom info in custom tables in the DB. I can't find in code the part when it stores the supplier to the db (I find only the part when it inserts the address relative to the supplier in ps_address table). Here the default postProcess() method: public function postProcess() { // checks access if (Tools::isSubmit('submitAdd'.$this->table) && !($this->tabAccess['add'] === '1')) { $this->errors[] = Tools::displayError('You do not have permission to add suppliers.'); return parent::postProcess(); } if (Tools::isSubmit('submitAdd'.$this->table)) { if (Tools::isSubmit('id_supplier') && !($obj = $this->loadObject(true))) { return; } // updates/creates address if it does not exist if (Tools::isSubmit('id_address') && (int)Tools::getValue('id_address') > 0) { $address = new Address((int)Tools::getValue('id_address')); } // updates address else { $address = new Address(); } // creates address $address->alias = Tools::getValue('name', null); $address->lastname = 'supplier'; // skip problem with numeric characters in supplier name $address->firstname = 'supplier'; // skip problem with numeric characters in supplier name $address->address1 = Tools::getValue('address', null); $address->address2 = Tools::getValue('address2', null); $address->postcode = Tools::getValue('postcode', null); $address->phone = Tools::getValue('phone', null); $address->phone_mobile = Tools::getValue('phone_mobile', null); $address->id_country = Tools::getValue('id_country', null); $address->id_state = Tools::getValue('id_state', null); $address->city = Tools::getValue('city', null); $validation = $address->validateController(); // checks address validity if (count($validation) > 0) { foreach ($validation as $item) { $this->errors[] = $item; } $this->errors[] = Tools::displayError('The address is not correct. Please make sure all of the required fields are completed.'); } else { if (Tools::isSubmit('id_address') && Tools::getValue('id_address') > 0) { $address->update(); } else { $address->save(); // here I want to get the ID of the inserted supplier $_POST['id_address'] = $address->id; } } return parent::postProcess(); } elseif (Tools::isSubmit('delete'.$this->table)) { if (!($obj = $this->loadObject(true))) { return; } elseif (SupplyOrder::supplierHasPendingOrders($obj->id)) { $this->errors[] = $this->l('It is not possible to delete a supplier if there are pending supplier orders.'); } else { //delete all product_supplier linked to this supplier Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'product_supplier` WHERE `id_supplier`='.(int)$obj->id); $id_address = Address::getAddressIdBySupplierId($obj->id); $address = new Address($id_address); if (Validate::isLoadedObject($address)) { $address->deleted = 1; $address->save(); } return parent::postProcess(); } } else { return parent::postProcess(); } }
You could use the hook actionObjectSupplierAddAfter to get the supplier object right after it was added to database using in your module something like: public function hookActionObjectSupplierAddAfter($params) { $supplier = $params['object']; }
Php system rating for photo gallery that allows 1 vote/day for each photo
I'm trying to develop a Php Photo Gallery only for my personal use and I put a Php System Rating using a modified script that I found on the web... all works fine except for one thing, I cannot stop users from posting several votes in the same day! I'd like that users vote the photos (several photos as well) but voting one time in the same day (one vote for each photo)... I post here the script that I have modified. ratings.php: <?php $rating = new ratings($_POST['widget_id']); isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote(); class ratings { var $data_file = './ratings.data.txt'; private $widget_id; private $data = array(); function __construct($wid) { $this->widget_id = $wid; $all = file_get_contents($this->data_file); if ($all) { $this->data = unserialize($all); } } public function get_ratings() { if ($this->data[$this->widget_id]) { echo json_encode($this->data[$this->widget_id]); } else { $data['widget_id'] = $this->widget_id; $data['number_votes'] = 0; $data['total_points'] = 0; $data['dec_avg'] = 0; $data['whole_avg'] = 0; echo json_encode($data); } } public function vote() { # Get the value of the vote preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match); $vote = $match[1]; $ID = $this->widget_id; # Update the record if it exists if ($this->data[$ID]) { $this->data[$ID]['number_votes'] += 1; $this->data[$ID]['total_points'] += $vote; } else { # Create a new one if it doesn't $this->data[$ID]['number_votes'] = 1; $this->data[$ID]['total_points'] = $vote; } $this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1); $this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']); file_put_contents($this->data_file, serialize($this->data)); $this->get_ratings(); } # --- # end class } ?> ratings.js: $(document).ready(function() { $('.rate_widget').each(function(i) { var widget = this; var out_data = { widget_id : $(widget).attr('id'), fetch: 1 }; $.post( 'ratings/ratings.php', out_data, function(INFO) { $(widget).data('fsr', INFO); set_votes(widget); }, 'json' ); }); $('.ratings_stars').hover( function() { $(this).prevAll().andSelf().addClass('ratings_over'); $(this).nextAll().removeClass('ratings_vote'); }, function() { $(this).prevAll().andSelf().removeClass('ratings_over'); set_votes($(this).parent()); } ); $('.ratings_stars').bind('click', function() { var star = this; var widget = $(this).parent(); var clicked_data = { clicked_on : $(star).attr('class'), widget_id : $(star).parent().attr('id') }; $.post( 'ratings/ratings.php', clicked_data, function(INFO) { widget.data('fsr', INFO); set_votes(widget); }, 'json' ); }); }); function set_votes(widget) { var avg = $(widget).data('fsr').whole_avg; var votes = $(widget).data('fsr').number_votes; var exact = $(widget).data('fsr').dec_avg; window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes); $(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote'); $(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote'); $(widget).find('.total_votes').text( votes + ' votes (' + exact + ' rating)' ); } I tried to implement IP mechanism in ratings.php as below without lucky <?php $rating = new ratings($_POST['widget_id']); isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote(); class ratings { var $data_file = './ratings.data.txt'; private $widget_id; private $data = array(); function __construct($wid) { $this->widget_id = $wid; $all = file_get_contents($this->data_file); if ($all) { $this->data = unserialize($all); } } public function get_ratings() { if ($this->data[$this->widget_id]) { echo json_encode($this->data[$this->widget_id]); } else { $data['widget_id'] = $this->widget_id; $data['number_votes'] = 0; $data['total_points'] = 0; $data['dec_avg'] = 0; $data['whole_avg'] = 0; echo json_encode($data); } } public function vote() { # Get the value of the vote preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match); $vote = $match[1]; $ID = $this->widget_id; # Update the record if it exists if ($this->data[$ID]) { $this->data[$ID]['number_votes'] += 1; $this->data[$ID]['total_points'] += $vote; $this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR']; } else { # Create a new one if it doesn't $this->data[$ID]['number_votes'] = 1; $this->data[$ID]['total_points'] = $vote; $this->data[$ID]['remote_ip'] = $_SERVER['REMOTE_ADDR']; } if ($this->data[$ID]['remote_ip'] != $_SERVER['REMOTE_ADDR']) { $this->data[$ID]['dec_avg'] = round($this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1); $this->data[$ID]['whole_avg'] = round($this->data[$ID]['dec_avg']); file_put_contents($this->data_file, serialize($this->data)); $this->get_ratings(); } } # --- # end class } ?>
The simplest way is to notify in a data table who vote and which day. For example : Toto vote on 2014-07-04, so he can't vote twice today. In data table user you add a colum date to notify the last day of vote. You can use cookies but it's very very ugly !
Execution of mySQL query in jQuery.Post method
I have created a javascript file that contains js to trigger an event onchange of a drop down list. The JS is below: // /public/js/custom.js jQuery(function($) { $("#parent").change(function(event){ event.preventDefault(); var parentID = $('#parent').val(); var id = $('#id').val(); $.post("/menu/GetMenuChildren", {pID: parentID, thisID: id }, function(data){ if(data.response === true){ var $el = $("#Position"); $el.empty(); // remove old options $.each(data.newOptions, function(key, value) { $el.append($("<option></option>") .attr("value", value).text(key)); }); } else { // print error message alert("something went wrong in Post"); } }, 'json'); alert("After Post"); }); }); In my Controller.php I have an function GetMenuChildrenAction as shown below: public function GetMenuChildrenAction() { $request = $this->getRequest(); $response = $this->getResponse(); if ($request->isPost()) { $post_data = $request->getPost(); $parent_id = $post_data['pID']; $id = $post_data['thisID']; //$this->form->get('Position')->SetOptionValues( $newOptions = $this->getMenuTable()->GetPositionsByID($parent_id, $id); if(isset($newOptions)) { $response->setContent(\Zend\Json\Json::encode(array('response' => true, 'newOptions' => $newOptions))); } else { $response->setContent(\Zend\Json\Json::encode(array('response' => false))); } } return $response; } In the MenuTable.php there is a Method GetPositionsByID as shown below: public function GetPositionsByID($parentID, $id) { if($parentID == 0) { $menu = $this->getMenu($this->id); $parentID = $menu->parent_id; } if(isset($parentID)) { $sql = "Select ID,Label from Menu Where parent_ID = " . $parentID . " and id > 1 and id <> " . $id . " Order by Position,Label"; try { $statement = $this->adapter->query($sql); } catch(Exception $e) { console.log('Caught exception: ', $e->getMessage(), "\n"); } $res = $statement->execute(); $rows = array(); $i = 0; foreach ($res as $row) { $i = $i + 1; $rows[$i] = array ( $i => $row['Label'] ); } return $rows; } return array(); } It all seems to be hooked up correctly, when I debug the code, I get the this line: $statement = $this->adapter->query($sql); and then nothing happens. If I replace all the code in the GetPositionsByID method, and simply return an array like the following: return array('1' => 'one', '2' => 'two'); it works great, however i want to get the data from the DB. Does anyone know why the execute would fail on this line? $statement = $this->adapter->query($sql); Thanks in advance
The issue was that the adapter was null.