Rafay
Rafay

Reputation: 24265

Update element after successful AJAX call

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">
        <a href="process.php?id=$id&f=u" class="upvote"><button>Upvote!</button></a>
        <a href="process.php?id=$id&f=d" class="downvote"><button>Downvote!</button></a>
    </div>
</div>

Returned by PHP

The updated number of upvotes.

Upvotes: 0

Views: 2446

Answers (3)

Quentin
Quentin

Reputation: 943165

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

Upvotes: 7

semir.babajic
semir.babajic

Reputation: 741

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.

Upvotes: 4

David Hellsing
David Hellsing

Reputation: 108480

$(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 //...

Upvotes: 1

Related Questions