gmail like star button -jquery problem - php

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.

Related

innerhtml+= How to Get load data from ajax then make an action?

im newbie that newbie learn here...
i want add some event from loaded part dynamically but it return to 1 id
so i problem with innerHTML+= and call with ajax like this..
$.ajax({
url: 'getuser.php',
type: 'POST',
data: {
id_user: id_user
},
success: function(data) {
listuser.innerHTML+=data;
}
});
then with getuser.php i got result like this
<div id="listuser">
<button id="1" class="pickmember">Member1</button >
<button id="2" class="pickmember">Member2</button>
</div>
so when i call a function
$(".pickmember").click(function(){
var id_user=$(this).attr('id');
alert('u pick member'+id_user);
});
when i call it,, it always return to last added to innerhtml, and cant detect member2 when click,, there is solution to this?
use .on() instead of .click()
$(".pickmember").on('click', function () {
var id_user = $(this).attr('id');
alert('u pick member' + id_user);
});
more information --> jQuery $(".class").click(); - multiple elements, click event once

AJAX overwritting

I'm currently using AJAX for live submit a post which is then appended to a list. The problem I am having is when I submit a post more than once, AJAX overwrites the previous posts submitted.
var data = $("#form_write_post").serialize();
$.ajax({
type: "POST",
url: $("#form_write_post").attr("action"),
data: data,
beforeSend: function() {
$("ul.timeline").prepend("<img class='textarea_ajax_loading' src='img/ajax-loader.gif' style='margin: 0 auto; display: block;' />");
},
complete: function() {
$('.textarea_ajax_loading').remove();
},
success: function () {
//var successCount = successCount++;
$("ul.timeline").prepend('<li class=ajax_post></li>').fadeIn();
$("ul.timeline .ajax_post").load("ajax_post.php").fadeIn();
//$('ul.timeline').prepend(wall_post);
//console.log("success");
return false;
}
});
How can I achieve a new post after each submission?
Thanks
I'm not sure that I fully understand your problem, but when you say "AJAX overwrites the previous posts submitted" I assume the problem is on the front-end right?
From the code I see, it might be because you prepend a new <li class=ajax_post></li> and then you select all the li with this class and load something in all of them.
If you want to load something only in the latest li, change the selector to
$("ul.timeline .ajax_post:first").load("ajax_post.php").fadeIn();
to select only the first post.
you're inserting the new content into every child of the same class. instead of using classes you should be using IDs: declare count outside your Ajax call and then do the following.
success: function () {
count = count++;
$("ul.timeline").prepend('<li class=ajax_post id="post'+count+'"></li>').fadeIn();
$("#post"+count).load("ajax_post.php").fadeIn();

Why do both ajax calls run when I submit a single input?

I am dynamically generating two paragraphs and two input fields inside a div. There may be numerous divs generated, depending upon the number of records pulled from the database. Each para and input field is assigned a unique id.
When the user clicks on a field, say firstText_id, jQuery hides the field and shows an input field firstText_input_id in its place. The user updates the input field, and on clicking away, an ajax script is called to update the database and return a success message.
My problem is that, when the user clicks on one field in any record, and updates it, then clicks away, the ajax calls for both fields are made.
PHP
echo "<div class=\"single seven columns boxTable2 \" id=\"{$vid}\">
<div class=\"seven columns alpha omega\" >
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega firstHead\">First name: </p>
<p class=\"firstText single two columns alpha omega\" id=\"firstText_{$vid}\"
data-vid=\"{$vid}\">{$first}</p>
<input type=\"text\" id=\"firstText_input_{$vid}\"
class=\"firstText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$first}\"/>
</div>
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega lastHead\" >Last name: </p>
<p class=\"lastText single two columns alpha omega\" id=\"lastText_{$vid}\"
data-vid=\"{$vid}\">{$last}</p>
<input type=\"text\" id=\"lastText_input_{$vid}\"
class=\"lastText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$last}\"/>
</div>
</div>
</div>
jquery
jQuery.noConflict();
jQuery(document).ready(function($){
var vidID = '';
$(document).on('click', '.firstText', function ()
{
vidID=$(this).data('vid');
$('#firstText_'+vidID).hide();
$('#firstText_input_'+vidID).show();
}).change(function()
{
var newFirstText=$('#firstText_input_'+vidID).val();
var firstTextDataString = 'vid='+ vidID +'&first='+newFirstText;
if(newFirstText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: firstTextDataString,
cache: false,
success: function(html)
{
$('#firstText_'+vidID).html(newFirstText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$('.firstText_input').mouseup(function(e)
{
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// return false; //(does the same as the above 3 functions)
});
// Click away action
$(document).mouseup(function()
{
$('.firstText_input').hide();
$('.firstText').show();
});
$(document).on('click', '.lastText', function ()
{
vidID=$(this).data('vid');
$('#lastText_'+vidID).hide();
$('#lastText_input_'+vidID).show();
}).change(function()
{
var newLastText=$('#lastText_input_'+vidID).val();
var lastTextDataString = 'vid='+ vidID +'&last='+newLastText;
if(newLastText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: lastTextDataString,
cache: false,
success: function(html)
{
$('#lastText_'+vidID).html(newLastText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".lastText_input").mouseup(function()
{
return false;
});
// Click away action
$(document).mouseup(function()
{
$(".lastText_input").hide();
$(".lastText").show();
});
});
As the unique IDs are generated dynamically from the database records, I can’t find a way of associating the user’s click to the field being updated without the other field in the record being updated. I’m a relative beginner with jQuery/javascript. How can I isolate the user’s action to the field being clicked? I have tried click selectors like ‘[id^=”firstText_input_”]’. Probably a simple error, but I have been round it too many times to see the error.
The event that causes the ajax to happen is actually bound to the document, therefore, anytime ANY input changes, the document receives the event and performs the ajax request.
See below:
$(document).on('click', '.someclass', function () {...}).change(function () {...});
.change is targeting $(document), not $('.someclass'), you'll have to use the same delegation syntax as before to instead delegate it to the target element.
$(document).on('click', '.someclass', function () {...}).on('change', '.someclass', function () {...});
both firstText and lastText are affected by this issue, which is why both trigger any time you change either input.
Additionally... your event binding is very inconsistent. In some cases you're using delegation, and in others you are not. Since you're replacing the entire content of the div, you should be using event delegation for all of the events within that div.

Passing PHP through JQuery.Ajax Post & Changing html

I'm trying to create a facebook style like/unlike link and I need to pass some php variables through the JQuery. At the moment I'm passing:
<a class="likelink" href="like.php?id=****&username=****&type=****">Like</a>
But although this works it is refreshing the page and I want it to do it fluently like twitter or facebook, so I need to pass the id, username, etc through JQuery.Ajax post. Can anyone tell me how this would be possible? Also then I want the .likelink to change to Unlike.
Thanks
Use an ajax request for the 'like' action and then change the class in the success callback function:
$('.likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'like.php',
data: {
id: ***,
username: ****,
type: ****
},
success: function() {
$('.likelink').removeClass('likelink').addClass('unlikelink');
}
});
});
You could do something along the lines of:
$('.likelink').on('click', function(e){
var $this = $(this);
$.get($this.attr('href'), function(){
$this.addClass('liked').attr('href', unlikeLink).text('Unlike');
});
e.preventDefault();
});

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