shanebp
shanebp

Reputation: 1956

ajax firing for every button when a single button is clicked

I'm adding a button to every list_item on page. The buttons are generated, with their correct id. And the button value changes as it should - as shown in the alert.

But on a single button click, the alert fires as many times as there are buttons on the page. The alert always shows the same (and correct) button id. Without the alert, this causes the button value to switch back and forth if other buttons are clicked in the meantime.

Generate the buttons:

function create_saved_message_button( ) { 
    $button_label = "Save";
?>
    <td width="15%" class="thread-options">
        <input type="button" class="savedbutton" value = "<?php echo $button_label ?>"  id = "<?php echo message_thread_id(); ?>" />
    </td>   
<?php
} 

The ajax:

function saved_message_button_javascript() {
?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        $('.savedbutton').click(function(event){
         event.preventDefault();
            var button = $(this);  
            var butt_txt = $(button).attr('value');

            alert($(button).attr("id"));

            $(button).attr({'disabled': true});
            var data = {
                action: 'saved_button_clicked',
            };

            $.get(ajaxurl, data, function(response) {
                if(butt_txt == 'Save') {
                    $(button).attr('value', 'Un-Save');
                }
                else {
                    $(button).attr('value', 'Save');
                }
            });
            $(button).attr({'disabled': false});
            return false;
        });

    });
    </script>
<?php
}

Is there any way to stop the multiple alerts? I think that would solve the value switching problem.

Then I just need to pass the button id to the php function saved_button_clicked

The add_actions:

    add_action( 'messages_inbox_list_item', 'create_saved_message_button', 1 ); 
//this was the problem
    //add_action('messages_inbox_list_item', 'saved_message_button_javascript');
//the solution - use this instead
add_action('after_member_messages_threads', 'saved_message_button_javascript');
    add_action('wp_ajax_saved_button_clicked', 'process_save_button_clicked');

Upvotes: 1

Views: 133

Answers (1)

dragon66
dragon66

Reputation: 2715

Maybe I misunderstood something. I created a html with 5 buttons and your javascript in it but I couldn't find the behavior you described. Look here.

Upvotes: 1

Related Questions