View Single Post
Old 05-28-2012, 12:18 PM   PM User | #1
johndoe
New to the CF scene

 
Join Date: May 2012
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
johndoe is an unknown quantity at this point
Using ajax to transform links after they have been clicked to update a database

On a page I have links (produced by a PHP loop) which look like this:

Code:
<div class="tools">
<a href="processor.php?c=cars&p=2&s=d&u=i&link=5&pid=999999990" title="Click to LIKE this photo" class="like do_like">&nbsp;</a>
</div>

<div class="tools">
<a href="processor.php?c=cars&p=2&s=d&u=d&link=6&pid=999999991" title="Click to UNLIKE this photo" class="like do_unlike">&nbsp;</a>
</div>
Note that each link has two classes: firstly a "like" class, and then either a "do_like" class or a "do_unlike" class, according to whether it's a link to "like" or a link to "unlike". (Originally I only had the "do_like" and "do_unlike" classes, as they're used to transform the link via css into a rollover-type image/icon, but I added the "like" class as well, as I thought it might be needed to do the ajax - see below.)

When a user clicks one of these links, the receiving processor.php script takes the key-value pairs from the query string, and uses them to update a database and then build a new form of the link. (The new form of the link is such that a "like this" link turns into an "unlike this" link, and vice-versa.) It does all this successfully.

What I want to do is use ajax (as I understand, best using jquery) to insert this newly built link in place of the one that was clicked, without having to refresh the page.

As I understand it, to make this happen, I need to include jquery, and also place a js function in the head section of the page. I tried this js function suggested on another forum for the purpose:


Code:
<script type="text/javascript">
$("a.like").click(function(e){
    e.preventDefault();
    var link= $(this);
    $.get(
        $(this).attr('href'),
        function(data){
            console.log('Successful! '+data);
            link.attr('href',data);      // Set the new link
            $link.append(' was toggled');// Add some text
    });
    $(this).parents('div.tools').fadeOut('slow');
});
</script>
This function doesn't work at all, however. All that happens is, the browser goes to the processor.php page, which echoes the newly built link.

What function would work for me?
johndoe is offline   Reply With Quote