jQuery Rating System Modification - php

I have built a jQuery 5 star rating system, ratings are inserted/stored in database along with no of hits, I am having a problem in inserting rating into database when any star is clicked repeatedly.
I.e., if a star is continuously clicked the rating does not get inserted but hits get inserted which then effect the new resulting rating.
I need to add some delay or stop the click function to fire again, it would be better if a delay can be added to click function.
I am trying stop click function to fire again this way but its not working.
jQuery:
$('.u-rating').click(function (e){
var id = $(this).parent().attr('id');
var rating = ($(this).index()+1)/2;
$.ajax({
type: "POST",
url:"rating.php",
data: {rating:rating, id:id},
cache: false,
success: function(data1)
{
get_rating();
$('#u-rating p').html('Rating Submitted');
}
});
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
How do I stop people from rating multiple times?

I would suggest that your real issue that your backend is registering just the hits but not the ratings - and you should probably focus on fixing the issue, not covering it with a band-aid.
Nevertheless, to address your question: You can use one() to bind the click handler just one, and then re-bind on every success (and error). See this jsfiddle for an example. Here is the code:
HTML:
<button id="button">Vote!</button>​
JS:
var postClick = function () {
console.log('click fired!!');
el = $(this);
el.prop('disabled', true);
//var id = $(this).parent().attr('id');
//var rating = ($(this).index()+1)/2;
$.ajax({
type: "POST",
url:"/echo/json/",
//data: {rating:rating, id:id},
cache: false,
success: function(data1){
//get_rating();
//$('#u-rating p').html('Rating Submitted');
console.log('ajax success, starting timeout peridod. Clicks will not register now, for the next 5 seconds!');
setTimeout(function() {
$('#button').one('click', postClick);
el.prop('disabled', false);
console.log('Clicks are re-enabled!');
}, 5000);
}
});
}
$('#button').one('click', postClick);
​

If your voters are logged-in users, store all ratings made by these users in a table with their user_id, then there's absolutely no problem keeping track of votes. If not, store them in a table with a date and an ip-address.
Since ip's can renew and point to a different user after an approximate interval, you can set a timeout date of about at day/week or so. This would have the drawback that users can keep voting once a day/week (if they haven't changed ip's), I don't know if that's acceptable in your project.
Then you can just (pseudo-code)
if (not exists sql("select rating from voteditems
where ipaddress = #ip_adress // Switch to "user_id" if that's what you're using
and item_id = #item_id
and datevoted > getdate()-1")) // Or -7 or whatever interval you choose
{
insert_rating();
}
The hits can be counted as
select count(rating) from voteditems where item_id = #item_id

Related

datePicker need to click twice to show the unavailable dates

I've created a code which disable certain dates retrieved from database.
Within getDates script I just retrieve dates from database, return them and assign them to array unavailableDates.
<script>
var unavailableDates;
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(document).ready(function()
{
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: unavailable,
minDate: 0,
firstDay: 1, // rows starts on Monday
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
altField: '#date_due',
altFormat: 'yy-mm-dd'
});
$('#datepicker').focus(function(){
//alert($('#name').html());
$.ajax({
url: 'getDates.php',
data: "artist_id="+$('#name').html(),
dataType: 'json',
success: function(data)
{
unavailableDates = data;
}
});
})
});
</script>
It works fine but only when I click in datepicker twice. When I first click it shows all dates (no matter if they are available or not). When I click again, then it shows the unavailable dates.
Does anyone know why? Thanks
Add async: false into your ajax call so the app will wait for the response before continuing, like so
$('#datepicker').focus(function(){
//alert($('#name').html());
$.ajax({
url: 'getDates.php',
data: "artist_id="+$('#name').html(),
dataType: 'json',
async: false,
success: function(data)
{
unavailableDates = data;
}
});
Another thought, you could possibly add this ajax call right into the unavailable function rather then having two things that run first, onFocus and beforeShowDay (although I'm not terribly familiar with the beforeShowDay function)
This may slow down the opening of the date picker though, as it will have to wait for the service so it depends on how fast your service is and what performance requirements you have. Other options if this can be to slow would be to pop up a "getting dates" message or pull the server every X seconds while the page it up (although that could add a lot of extra service calls...)
EDIT: After this comment...
"basically when user selects an option (here they want to book artists so \
when user selects an artist), the unavailable dates of datepicker are
updated automatically."
it seems like loading the list when the artist is selected would make more sense, unless your concerned about changes while the page is open. In that case I would do something like...
On Artist Changed
-Disable date picker, possibly add a small note next to it / under it /
over it that it is loading
-Start ajax call with async true
-In ajax success function, re-enable the picker and remove the message.
This will allow the UI to stay active, allow the user to enter other information while the dates load, and if the service is fast enough, the won't even hardly know it was disabled for a second. Your dates won't be quite a "live" as the other way, but it doesn't sound like they need to be that live. You will need to recheck the dates when the form is submitted anyway.
Because you start the request for getting the unavailable dates when the datepicker is displayed. You have to do this in advance. In the callback of the backend request you can display the datepicker.
var data = $.getJSON($url, function (data) {
//your logic
}).success(function (data) {
//Trigger the first click
$('.datepicker').trigger('click');
});
$(".div_fader").on('click','.datepicker', function () {
$(this).datepicker();
});

Dynamically change dropdowns via SQL and calculate sums?

I've got a row in a table with 3 fields laid out as so:
Job Pay Grade Cost
<Select> <Select> <Calculation>
I've got an SQL table with the information above in it, for example:
Job Pay Grade Cost
Techie 1 100
Techie 2 200
Engi 2 300
Engi 3 400
Engi 4 500
What I need to do is to be able to select a Job from the dropdown and then the Pay Grade select box will change depending on what matches that job in the SQL database. It will then show the cost which relates to the to selected.
How can I go about this as I am a little stuck
First create ajax request when a job title is selected. WIthin the success callback of the request will generate html for the options for pay grade select from JSON response from server
jQuery
$('select.jobTitle').change(function(){
var $titleSelect=$(this);
$.getJSON('processJobGrades.php', { jobTitle : $(this).val() }, function(response){
var gradesOptionsHtml='';
/* create options html from json response */
$.each( response, function(i, item){
gradesOptionsHtml+='<option value="'+item.grade+' data-cost="'+item.cost+'">'+item.grade+'</option>';
});
$titleSelect.parent().find('select.jobGrade').html(gradesOptionsHtml);
});
});
IN processJobGrades.php receive $_GET['jobTitle'] . Do DB lookup and create json to send back.
PHP
$outputArray=array();
/*in loop over DB data:*/
$outputArray[]= array( 'grade'=>$row['grade'], 'cost'=>$row['cost']);
/*Output final array as JSON*/
echo json_encode( $outputArray);
jQuery change handler for paygrade select to get cost
$('select.jobGrade').change(function(){
var cost=$(this).find(':selected').data('cost')
$(this).parent().find('input.jobCost').val( cost);
})
You need to post the select job via $.ajax and then in success function populate the dropdown list like this:
function selectHandler (event, ui)
{
var id = event.target.id;
$.ajax({
type: "POST",
url: "/php/get_quantity_type.php",
dataType:"json",
data: { ingridient : ui.item.value},
success: function(data){$("#"+id+"_t").empty(); $.each(data,function(index,value) {$("#"+id+"_t").append('<option value="' + value + '">' + value + '</option>');})}
});
}
This example takes a name of a material from select list posts it via $ajax() to a php script and writes it down to a new dropdown list which id is based on id that triggered the event. If you need the php code just ask:)
You bind your job list to the event handler above:
("#job_list").bind("select",selectHandler);
This code posts data to "/php/get_quantity_type.php", and passess the result to function declared in success attribute;

jQuery UI & PHP - Sending 'To' Column to PHP

I am using jQuery UIs Sortable to allow a user to move items from 4 columns as well as change the order of items within each column. I have the latter working without problem; updating the new order to the database.
But I'm not sure how to handle storing moving from Column A to Column B. Each unordered list has a unique ID so I'd like to send that information along; I just don't have a firm understanding of how to do this.
$("#list1, #list2, #list3, #list4").sortable({
connectWith: ".sort",
placeholder: "shadow",
dropOnEmpty: true,
opacity: 0.8,
cursor: 'move',
update: function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("/update.php", order, function(theResponse) {
$("#alert").html(theResponse);
$("#alert").slideDown('slow');
slideout();
});
}
});
I've found an answer to my own question. The answer is to pass the data to the PHP file in a slightly different manner that allows for a more robust amount of variables (rather than just serializing one set of information).
var item = ui.item;
var new_ul = item.parent();
var order = [];
container.children('li').each(function(i){
reorder[i] = $(this).attr('id');
});
$.ajax({
method:'post',
url: 'update.php',
data:{
'new_ul':container.attr('id'),
'item':item.attr('id'),
'order':order
}
});
Full credit for this solution goes to user 'Zehee' at CodeIgniter (Who I believe got the solution from 37signals) http://codeigniter.com/forums/viewthread/175134/#831756

gmail like star button -jquery problem

I've built star button to use it like "starred items". I have the code running. but i have a problem.
When i click on star it becomes a starred item and and the star image changes.
But when i click again to unstar, it just doesn't work. i need to refresh the page to unstar it.
Also even the first step doesn't work for chrome.
add star codes:
jquery
$(function() {
$(".yildiz").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "yildizekle.php",
data: dataString,
cache: false,
success: function toggle()
{
$('.yildizbutton'+id).animate({
src:"star-icon.png",
class:"yildizsizbutton"+id,
},0);
}
});
return false;
});
});
php:
<img class="yildizsizbutton'.$row['id'].'" border="0" src="star-icon.png" alt="Yildizi kaldir" width="16" height="16" />
remove star
$(function() {
$(".yildizf").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "yildizsil.php",
data: dataString,
cache: false,
success: function toggle()
{
$('.yildizsizbutton'+id).animate({
src:"star-icon-f.png",
class:"yildizbutton"+id,
},0);
}
});
return false;
});
});
php:
<img class="yildizbutton'.$row['id'].'" border="0" src="star-icon-f.png" alt="Yildiz ekle" width="16" height="16" />
To add the star, do something similar to this:
$("#"+id).find("img").attr("src", "star-icon.png");
To remove:
$("#"+id).find("img").attr("src", "sstar-icon-f.png");
You shouldn't use animate in the way you are using it at all. I also used the ID of the container, then found the image inside of it, instead of putting together that class like you were doing. That's just personal preference, though...the main takeaway is to use attr("src") to set the src of an image in jQuery.
EDIT: Here is a full solution that should work.
$(function() {
$(".star").click(function() {
var id = $(this).attr("id");
if($(this).hasClass("starred")) {
$.post("yildizekle.php", {id: id}, function(resp) {
$(this).removeClass("starred").find("img").attr("src", "star-icon-f.png");
});
}
else {
$.post("yildizsil.php", {id: id}, function(resp) {
$(this).addClass("starred").find("img").attr("src", "star-icon.png");
});
}
return false;
});
});
Notice that we are using a class to track whether or not the element is already starred. This means in your PHP you will need to add the starred class to any elements that are already starred when the page loads. Also, I used $.post instead of $.ajax since it is a simpler way of doing the same thing.
There are a few problems in your code, and both of the answers here are relevant and both are correct. Being as green as you are, I'd say you are on the road to learning well.
I'd use a separate class for ALL of the stars, one that doesn't relate to if its starred or unstarred. Maybe something like 'star'. :) You need to refresh the page to un-star it is because you never actually change it on the FRONT-end to be starred. If you use a tool like firebug of WebKit's Web inspector, you'll see that the class of the link is still "yildiz".
I'm not going to give you a complete answer because I'd be robbing you of an awesome learning experience here. Here are some pointers:
Remember which objects your click() events are connected to: $(".yildizf") and $(".yildiz")
When you click on an item, does it actually change class so that jQuery knows it's different? Essentially, you are 'starring' the same item over and over again because you never allow jQuery to see it as something it needs to un-star
If you use a 'star' class in addition to the other class (like <a class="star yildiz" ...>), then you can attach your click event to $('a.star'), and figure out in THERE if you should be starring or unstarring the item.
I hope this all makes sense.
You've defined the click event to both star and un-star the item. In the event you need to look at the current state of the item then decide if you want to star or un-star it. you need to branch inside your click event.

jQuery, need help with 'sortreceive' ajax call and POST vars

I have a dilemma that just seems beyond my abilities at the moment!
I have a group of connected sortables using the class 'biglist'.
What I want to do is bind #biglist 's sortreceive callback (which is made whenever a list receives an element from another) to take the 'boxnum' value of the element (which signifies which list its coming from) and perform an UPDATE query changing the id's boxnum value from say 5(list it came from) to 7 (list its been dragged to) so that the state persists.
So the exchange would happen like so (roughly)
$( "#biglist" ).bind( "sortreceive", function(event, ui) {
ajax call to boxchange.php
create vars to represent elements 'boxnum' value and 'box moved to' value
});
Then inside boxchange.php ->
$id = $_POST['id']
$box = $_POST['boxnum']
->update query SET boxid to new boxid WHERE id = posted ID of element
I hope this makes sense. It seems like a pretty slick way to make my program work!
Any help is greatly appreciated.
EDIT:
Just cleaned up the function to see if there are any changes that need to be made to it (which I know there are, because it looks sloppy) This function would need to be copied/altered for each sortable separately but it'd totally make the program work at least!
function ReceiveTwo()
{
$('#sortable2').bind('sortreceive', function(event, ui)
{
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
$.ajax
({
url: "boxchange.php",
type: "POST",
data: boxnum, id,
success : function(feedback)
{
$('#data').html(feedback)
}
})
});
$('#sortable2').sortable("refresh");
});
$('#sortable2').bind('sortreceive', function(event, ui) {
$.ajax({
url: "boxchange.php",
type: "POST",
beforesend: function(){
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
},
data: {'boxnum': boxnum, 'id': id},
success : function(feedback) {
$('#data').html(feedback),
}
});
});
beforesend is the event that fires before the ajax call. I believe here you could set your properties to accomplish what you want.
I think the way you want to send your Javascript data to your server-side PHP script is using a Javascript associative array, like so:
$.ajax({
url: "boxchange.php",
type: "POST",
data: {'boxnum': boxnum, 'id': id},
success: function(data,status) { ... }
Your "boxchange.php" script would then be able to access those variables via $_POST['boxnum'] and $_POST['id'].
I think that was your goal, but I'm not entirely sure...

Categories