开发者

using jquery/ajax to send/update div when link is clicked

开发者 https://www.devze.com 2022-12-11 19:12 出处:网络
I have 2 layers that i need to update individually if a user clicks on either of them. <div id=wrapper>

I have 2 layers that i need to update individually if a user clicks on either of them.

<div id=wrapper>
    <div id=upvote>
        //This div can be filled by upvote.php?id=X
        <? ec开发者_JS百科ho getUpVote(); ?>
        <a href=#><img src=upv.png></a>
    </div>
    <div id=downvote>
        //This div can be filled by downvote.php?id=X
        <? echo getdownVote(); ?>
        <a href=#><img src=downv.png></a>
    </div>
</div>

When the user clicks the up or down vote image, i need to fade out the contents of the div, make an ajax call to the respective php file (get request), and fade in the loaded content.

How can i do this?


Attach a click handler to the anchor tags. Find which url to use given the id of the containing div, then invoke load to replace the contents of the wrapper. Fade out/in at the appropriate points. Make sure that you return false from the anchor click handler to cancel the default action.

$('#upvote,#downvote').find('a').click( function() {
    var url  = $(this).closest('div').attr('id') + '.php?id=X';
    $('#wrapper').fadeOut();
                 .load( url, function() {
                     $('#wrapper').fadeIn();
                 });
    return false; // cancel click action
});


To add a click handler to an element in jQuery you can do this:

 $("#upvote").click(clickHandler);

Where clickHandler is a function. Since you want to fade Out an image you can do this:

 $("#upimg").hide('slow');

will cause an element with id='upimg' to disappear slowly. You can also use fadeTo(opacity) to achieve a similar effect.

The AJAX call can be made with a call to load.

$('#div').load('url', {}, callback);

where an element with id='div' will be populated with the result of calling url, the {} is optional and callback is a function that you can include to execute after the load. The callback function may be used to fadeIn the new content.

 var clickHandler = function(){
    $("#upimg").hide('slow');

    $('#div').load('url', {}, callback);

 }

 var callback = function(){
    $('#div').show('slow');
 }


AJAX request can be made with $.get and you can fade the DIV using jQuery's animation functions like fadeOut

Here is some code on how you might acchive what you want:

$( '#IdOfOneAnchor' ).click ( function () {
    var myDiv = $( '#IdOfYourDiv' );
    myDiv.fadeOut ();
    $.get (
        'url/to/your/script.php',
        {
            // put params you need here
        },
        function ( response ) {
            myDiv.html ( response ).fadeIn ();
        }
    );

    return false;
} );

off course you will have to change the selectors to match your DIVs/links ...

0

精彩评论

暂无评论...
验证码 换一张
取 消