Problem
After a successful AJAX call, I want to update an element on page. However, it is not being updated.
Code [Javascript]
$(function()
{
$(".upvote").click(function()
{
var id = $(this).parent().find("input").val();
$.ajax(
{
type: "GET",
url: "process.php",
data: "id=" + id +"&f=u",
success: function(results)
{
$(this).parent().parent().find("span.ups").empty().append("Upvotes: " + results);
console.log(results);
}
});
return false;
});
});
Code [HTML]
This code is being generated by PHP.
<div class="post">
<h2>$title</h2>
<p>$body</p>
<span class="ups">Upvotes: $upvotes</span>
<span class="downs">Downvotes: $downvotes</span>
<span class="total">Total votes: $t_votes</span>
<div id="links">
<input type="hidden" id="id" name="id" value="$id">
<button>Upvote!</button>
<button>Downvote!</button>
</div>
</div>
Returned by PHP
The updated number of upvotes.
this is not what you think it is. Its value is determined by how the function it appears in is called (and will change when inside a different function).
I've no idea what it will be in a jQuery success callback, but it won't be an HTML element.
If you want it to be the clicked upon element, then you need to store it while this is that element.
$(".upvote").click(function() {
var clicked_element = this;
Then you can use that variable later on:
$(clicked_element).parent().etc
You cannot use this keyword like that.
var that = null;
$(function()
{
$(".upvote").click(function()
{
var id = $(this).parent().find("input").val();
that = $(this);
$.ajax(
{
type: "GET",
url: "process.php",
data: "id=" + id +"&f=u",
success: function(results)
{
that.parent().parent().find("span.ups").empty().append("Upvotes: " + results);
console.log(results);
}
});
return false;
});
});
I didn't test this, but it should work.
Cheers.
$(this) inside the success callback is not the element you might think it is. It would probably be better to cache the parent object instead and traverse from there:
var $post = $('.post');
//... $.ajax etc
success: function() {
$post.find('.ups').etc //...
Related
i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.
I have some JQuery handling a div click. If the div is clicked once it hides itself and shows another div (and posts to a php script in the background). If it is then clicked again, it's supposed to hide the new div, show the new one again, and post more data to a different script, and so on.
It changes the first time (.f hides, .uf shows) but when I click '.uf' nothing happens.
JQuery:
if($('.f').is(":visible")) {
$('#follow').click(function() {
var to_follow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/rel_p.php",
data: "y=" + to_follow,
success: function() {
$('.f').hide();
$('.uf').show();
}
});
});
}
else {
$('#follow').click(function() {
var to_unfollow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/relu_p.php",
data: "y=" + to_follow,
success: function() {
$('.uf').hide();
$('.f').show();
}
});
});
}
HTML:
<div id="follow" class="f">
<img src="img/icons/Follow.png">
<h1>Follow</h1>
</div>
<div id="follow" class="uf" style="display:none;">
<img src="img/icons/Unfollow.png">
<h1>Unfollow</h1>
</div>
use a class if you intend to use the selector twice, and don't write the same code twice unless you have to:
$('.follow').on('click', function() {
var is_f = $('.f').is(":visible"),
to_follow = $('.name').attr('id'),
give_me_an_u = is_f?'':'u';
$.ajax({
type: "POST",
url: "/bin/rel" + give_me_an_u + "_p.php",
data: {y : to_follow}
}).done(function() {
$('.f, .uf').toggle();
});
});
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.
im trying to pass on the id attribute to the file.php, but its giving me 0 every time, when i try to insert it into the database, the javascript and the html is provided!
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "file.php",
data: info,
success: function(){}
});
$("#follow"+I).hide();
$("#remove"+I).show();
return false;
});
});
html file:
<div id="follow1"><span class="follow_b"> Follow </span></div>
p.s. it deos insert the value in the database
file.php:
<?php
$id =$_POST['id'];
msql_insert.........
?>
It may not matter in this case, but the ID of an element is not supposed to start with a number.
I'll start off by saying I'm new to jQuery but I am really enjoying it. I'm also new to stackoverflow and really loving it!!
The problem:
I've created a sub-form with jQuery so that a user may add, then select this information from a dropdown list if it is not already available. I'm unable to POST this data with .ajax(), so that the user can continue to fill out other information on the main form without having to start over.
Sub-Form:
$(function() {
$("#add").live('click', function(event) {
$(this).addClass("selected").parent().append('<div class="messagepop"><p id="close"><img src="img/close.png"></p></img><form id="addgroup" method="POST" action="add_group.php"><p><label for="group">New Group Description:</label><input type="text" size="30" name="grouping" id="grouping" /></p><p><label for="asset_type">Asset Type:</label><select name="asset" id="asset" ><option>Building</option><option>Equipment</option></select></p><p><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></form><div id="result"></div></div>');
$(".messagepop").show()
$("#group").focus();
return false;
});
$("#close").live('click', function() {
$(".messagepop").hide();
$("#add").removeClass("selected");
return false;
});
});
And here is where I'm attempting to process it:
$(function () {
$('#addgroup').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
I've even attempted to create a simple alert instead of processing the information and this also does not work. Instead the form sumbits and refreshes the page as normal. Can anyone help me understand what I am missing or doing wrong? Thank you!
New attempt:
$("#add").live('click', function(event) {
var form = $("<form>").html("<input type='submit' value='Submit'/>").submit(function(){
$.post("add_group.php", {grouping: "Building, asset: "STUFF"});
$(".newgroup").append(form);
return false;
});
Final code
$(function() {
var id = 1
$("#add").live('click', function(event){
if($(".addgroup,").length == 0){
$("#test").append('<div class="addgroup"><label for="newGroup">New Group:</label><input type="text" class="newgroup" id="' + ++id + '" /><input type="submit" value="Add Group" name="group_submit" class="group_submit"/></div>');
$("#add").attr("src","img/add_close.png");
}else{
$("#add").attr("src","img/add.png");
$(".addgroup").remove();}
return false;
});
});
$(function(){
$(".group_submit").live('click',function(event){
$.ajax({
type: "POST",
url: "add_group.php",
data: {new_group: $(".newgroup").val(), asset: $("#group option:selected").text()},
success: function(){}
});
$(".addgroup").remove();
$('#subgroup').load('group.php', {'asset': $("#group option:selected").text()});
return false;
});
});
If the form is submitting and refreshing as normal, the jquery isn't kicking in (the refresh means it's posting the form normally).
I for some reason (maybe others haven't) found that $(document).ready(function() { works much better than $(function() { ...
Also, the groups that you're adding should have a definitive id:
on #add click, count up a counter (form++) and add that to the id (#addGroup_+form) and then target that straight away in the function that added it:
$("#group").focus();
$("#addGroup_"+form).submit(function() {
try using .live()
$(function () {
$('#addgroup').live('submit',function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(responseText) {
$('#result').html(responseText);
}
});
return false;
});
});
and make sure addgroup has no duplicate id... you may use it as class if it has to be duplicated...