having a problem with jquery votes just like stackoverflow votes? - javascript

i have this jquery code with an ajax request that works fine, but the jquery is not displaying the results(vote_count) and changing the upvote image, just like stackoverflow:
jquery code:
$(function(){
$("a.vote_up").click(function(){
//get the id
the_id = $(this).attr('id');
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id="+$(this).attr("id"),
url: "ajax/votes.php",
success: function(msg)
{
//echo the votes count
$("span#votes_count"+the_id).html(msg);
//replace the new vote count
$("span#votes_count"+the_id).fadeIn();
//replace the image with active arrow
$("#vote_up"+the_id).attr("src", "img/upvoteActive.png");
}
});
});
the html code:
<li class ="record">
<span class="vote_count">$net_vote</span>
</li>
to clarify everything again, the ajax request is fine its upvoting the right answer, the problem is in the success bit of the ajax, the new vote count is not showing, and the image is not being replaced to an active arrow(just like stack overflower) thanks :))

Your selectors in the success callback are all wrong. You have <span class="vote_count">...</span> but then try to update it's value as if it had an id: $("span#votes_count"+the_id)...
You probably want your code more like:
success: function(msg) {
//echo the votes count
$("span.vote_count#"+the_id).html(msg);
//replace the new vote count
$("span.vote_count#"+the_id).fadeIn();
//replace the image with active arrow
$(".vote_up#"+the_id).attr("src", "img/upvoteActive.png");
}
So as you can see, you'll also want to add the id of the object into the .vote_count element as well.
Update:
To be clearer, here is the updated markup:
<span class="vote_count" id="$id">$net_vote</span>
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
And here is the updated javascript:
$(document).ready( function() {
$("a.vote_up").click(function(){
//get the id
var the_id = $(this).attr('id');
//the main ajax request
$.ajax( {
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function( msg ) {
$("span.vote_count#"+the_id).html(msg).fadeIn();
$(".vote_up#" + the_id + " img").attr("src", "img/upvoteActive.png");
}
} );
} );
} );

In your jQuery code you use #votes_count but the html does not have an id but a vote_count class (without the s).
So it should read span.vote_count
same with the upvote, you use an id to target it but it has a class..

You were incorrectly targetting the spans, and also, sending get parameters over a post request. I have fixed below:
$(function(){
$("a.vote_up").click(function(){
//get the id
the_id = $(this).attr('id');
//the main ajax request
$.ajax({
type: "POST",
data: {'action' : 'vote_up','id' : $(this).attr("id")} // here
url: "ajax/votes.php",
success: function(msg)
{
//echo the votes count
$("span.vote_count").html(msg); //here
//replace the new vote count
$("span.vote_count").fadeIn(); // here
//replace the image with active arrow
$(".vote_up").find(the_id).attr("src", "img/upvoteActive.png"); // and here
}
});
});

Related

Jquery removing issue divs still remains

Yesterday I coded a Commentbox in PHP, HTML and ajax. The ajax part gives me the opportunity to delete a comment without refreshing the page. The way I do this, is that I give each and every comment (div) a unique id via the database. So let us for example say that in my mysql database this is how a comment looks like:
Username: blabla<br>
Comment: haha this is so funny<br>
id: 52
This will be printed out in the html page likes this for example:
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment">Delete the comment here!</div>
</div>
AND THEN!
Comes the ajax part which is coded something like this:
$(document).ready(function(){
$(".deleteComment").click(function(){
//Getting the id of comment
id = $(".deleteComment").attr("id");
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
});
This works fine when deleting the first comment. But it WONT LET ME DELETE OTHER COMMENTS UNLESS I REFRESH THE PAGE >.<. The first comment can be perfectly deleted without refreshing the page, but when I want to delete other comments I have to refresh the page multiple times.
How do I solve this?
The code in your document ready event would work properly only for the first click. In order to get this work, you must have an on click event registered within the tag.
Example :
<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>
function DeleteMe(id)
{
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
}
If the on click on a div does not work, you can use an anchor tag (Delete here) instead.
.deleteComment is child of <div class="commentStyle".., so you can select it with parent() selector:
var id = $(this).parent().attr("id");
Or more specifically:
var id = $(this).parent('.commentStyle').attr("id");
Looks like you need to get the id from the parent element first and then target the child, the element you clicked, to hide the comment from it after the ajax request returns success:
$(".deleteComment").click(function(){
var id = $(this).parent().attr("id");
var child = $(this);
$.ajax({
type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
child.hide();
// or if you want to delete the entire element with the id of X
// child.parent().hide();
}
});
});
There are few changes which need to be done in your code.
First of all add ID tag to the inner div.
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here! </div>
</div>
Secondly use this
id = $(this).attr("id");
instead of...
id = $(".deleteComment").attr("id");
Thirdly change the ajax call like this:
$.ajax({
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id
}).done(function(){
$("#" + id).hide();
});
Hope this works for you, if not just reply me.

Checking text of individual divs and changing content

I have repeats of the same code multiple times because of my PHP echoing the content out, and I want to interact with each div separately. It's hard for me to explain, but here's an example of the code repeated just twice. Hopefully it fully represents what I actually have...
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
<form id="favorite"><div id="images"><input type="submit" style="background-image: url(grey.png);" onclick="submit" value="" /></div></form>
javascript:
$('#favorite').submit(function() {
var url = document.URL;
if(document.getElementById("images").innerHTML.indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $("#favorite").serialize(),
success: function(data)
{
$('#images').html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});
So, if I were to click the image for the top form, it works perfectly. It will run the PHP and it will change the image without refreshing. If I click the bottom image, it will run the PHP, but it will refresh the page and it won't change the image. So it seems like if I click the bottom one, it doesn't like the Javascript. I don't know if it's because it's looking at both of the forms since they have the same ID (which I can't fix since it could possibly have hundreds), or something else, which I don't see any problems. I'm guessing there's some way to do it using "this", but I'm unsure of how to use it.
Thank you!
You need to change a few things. Your selector to bind the event only matches the first occurrence of #favourite as id's should be unique. You get around this by using an attribute equals selector.
In addition, ensure you select each sub-element in the context of the current form, similar to this:
$('[id=favorite]').submit(function () {
var $form = $(this); // the current form
var $image = $('#images', $form) // get images element in the context of current form
var url = document.URL;
if ($image.html().indexOf("grey") != -1) {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(red.png);\" onclick=\"submit\" value=\"\" />");
}
});
} else {
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), // use current form, don't re-select
success: function (data) {
$image.html("<input type=\"submit\" style=\"background-image: url(grey.png);\" onclick=\"submit\" value=\"\" />");
}
});
}
return false;
});

Using AJAX to Extract Data from IMDB API

I'm trying to get the year of a film given its title using IMDB's API and then appending the year in parenthesis next to the title.
There's some fundamental JS or AJAX thing that I'm screwing up. Any help would be much appreciated!
This is my code: jsFiddle
HTML
<ol>
<li>Jaws</li>
<li>The Lord of the Rings</li>
</ol>
jQuery
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + title,
dataType: 'jsonp',
success: function(data){
var year = data.Year;
}
});
}
$("li").each(function() {
var text = $(this).text();
getYear(text);
$(this).append(" ("+year+")");
});
Your code is calling the AJAX function, but immediately going on to update the page before the asynchronous function returns. You need to include the code that updates the page in the callback to the AJAX function so that it executes when the data is ready.
I have reworked your code to this:
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + $(title).text(),
dataType: 'json',
success: function(data){
var year = data.Year;
var text = $( this ).text();
$(title).append(" ("+year+")");
}
});
}
$( "li" ).each(function() {
getYear(this);
});
Which works successfully on this fiddle

Changing CSS class dynamically

I have an indicator on a page which is either a red or green circle.
<div class="publicBm changeState" currentstate="1" statusid="56" title="This is Public"></div> <!-- green -->
<div class="privateBm changeState" currentstate="1" statusid="57" title="This is Private"></div> <!-- red -->
When a user clicks the circle (which is a div with class changeState as shown above) an AJAX call is made to update the database to the opposite of what the item currently is, public or private. Then it returns the opposite class.
All works perfectly but I want to change the class on the circle clicked to reflect that the update has been successful.
Here's what I'm trying - as I said, the actual database call within the php file is perfect it's just that the div is not having it's class changed.
NOTE - there can be multiple lines on each page so I can't simply give the DIV an id
$('.changeState').click(function() {
var bm_id = $(this).attr('statusID');
var current = $(this).attr('currentState');
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
success:
function(data) {
$(this).removeAttr('class').attr('class', data + ' changeState');
}
});
});
Your issue is this. this is not the DOM element inside the ajax success callback. Instead set the context as that of the element so that this inside the callback now refers to the element and not jqXhr object.
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
context: this, //<-- Here
success:
function(data) {
this.className = data + ' changeState';
}
});
or use a cached context.
...
var self = this;
$.ajax({
type: "POST",
url: '/ajax/actions/editStateBm.php?bm_id='+bm_id+'&current='+current,
success:
function(data) {
self.className = data + ' changeState';
}
});
...
BTW what are you posting? you need to use GET?
$.ajax({
type: "GET",
....
Use .addClass()
success: function (data) {
$(this).removeAttr('class').addClass(data + ' changeState');
}
and removeProp
success: function (data) {
$(this).removeProp('class').addClass(data + ' changeState');
}
This should be something like:
$(this).removeClass('class').addClass(data + ' changeState');

My function only works with an alert after my ajax call

I'm populating a table with values from my database. I have included a delete icon in rows which can be deleted. The image has an onclick='deleteCat(id);' property, the id is taken from a json array trough a loop like so:
string = "<td align='center'><a href=''><img border='0' src='../images/Bullet-Delete.png' alt='delete' onclick='deleteCat("+json[i]['id']+");'/></a></td>";
This is my deleteCat function:
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
//$("#allecat").find("tr:gt(0)").remove();
//update_table();
}
});
//alert(id);
}
My function works when I put an alert after the ajax. The table refreshes and the row is removed from my db. However when I remove the alert my function does not work, the table is refreshed and the row is still present in the table and db.
Thanks in advance.
You need to prevent the default event for the click - ie the page is being reloaded each time you click on the image
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
$("#allecat").find("tr:gt(0)").remove();
update_table();
}
});
return false; // prevent the browser following the href
}
You will also need to change your html :
onclick='return deleteCat("+json[i]['id']+");
The alert() helps because that delays the processing of the remaining javascript in that function. The ajax send data asynchronously. async key is Default: true and should change it to false in your call till the client wait for end of ajax call.
e.g.:
$.ajax({
async:false,
url: "test.html",
.
.
});

Categories

Resources