简体   繁体   中英

Same AJAX call for multiple elements

I've read some answers that get close, but I'm still not able to connect the dots.

I have a bunch of checkboxes that write a 1 and 0 to a database using Ajax. As it is now, I have just copy/pasted the ajax function and the only thing that needs changed is the #id that it listens to.

How can I generalize the ajax so the code isn't so repetitive? Here's what I've got:

                    <label class="rep_label"><input type="checkbox" id="goal1admin" name="goal1hit" value="1" checked />
            This is my first goal</label>

                    <label class="rep_label"><input type="checkbox" id="goal2admin" name="goal2hit" value="1"  />
            Goal 2</label>

                    <label class="rep_label"><input type="checkbox" id="goal3admin" name="goal3hit" value="1" checked />
            3rd time is the charm</label>


<script type="text/javascript">
jQuery(document).ready(function($) {
    $("#goal1admin").change(function() { 
        if($(this).is(":checked")) { 
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"1", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal1admin').attr('checked', true); 
                },
                error:function(){
                    $('#goal1admin').attr('checked', false);                    }
            });
        } else {
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"0", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal1admin').attr('checked', false); 
                },
                error:function(){
                    $('#goal1admin').attr('checked', true); 
                }
            });
        }
    }); 
});
jQuery(document).ready(function($) {
    $("#goal2admin").change(function() { 
        if($(this).is(":checked")) { 
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"1", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal2admin').attr('checked', true); 
                },
                error:function(){
                    $('#goal2admin').attr('checked', false);                    }
            });
        } else {
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"0", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal2admin').attr('checked', false); 
                },
                error:function(){
                    $('#goal2admin').attr('checked', true); 
                }
            });
        }
    }); 
});
jQuery(document).ready(function($) {
    $("#goal3admin").change(function() { 
        if($(this).is(":checked")) { 
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"1", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal3admin').attr('checked', true); 
                },
                error:function(){
                    $('#goal3admin').attr('checked', false);                    }
            });
        } else {
            $.ajax({
                url: 'code.php',
                type: 'POST',
                data: { db_column:$(this).attr("name"), strState:"0", user:"admin" },
                success: function() { // this happens after we get results
                    $('#goal3admin').attr('checked', false); 
                },
                error:function(){
                    $('#goal3admin').attr('checked', true); 
                }
            });
        }
    }); 
});
$("input[type=checkbox]").change(function() {  
    var $input = $(this); 

    $.ajax({
        url: 'code.php',
        type: 'POST',
        data: { db_column:$input.attr("name"), strState:$input.is(":checked"), user:"admin" },
        success: function() { // this happens after we get results
            $input.attr('checked', true); 
        },
        error:function(){
            $input.attr('checked', false);
        }
    });
});

This attaches the handler to all checkboxes. I made it generic and simple so you don't to use conditionals.

jQuery(document).ready(function($) {
    //--------------------------------------------------------------------
    // use the class selector instead of id, this will allow you to do the
    // same for all elements with the same class
    //--------------------------------------------------------------------
    $(".rep_label input[type=checkbox]").change(function() { 
            //Cache the current element
            var $this = $(this);

            //cache the current checked state
            var checked = $this.is(':checked');
            var State = (checked)? "1":"0";

            //send ajax request
            $.ajax({
                url: 'code.php',
                type: 'POST',
                //set the state variable to the current element checked state
                data: { db_column:$this.attr("name"), strState:state, user:"admin" },
                success: function() { // this happens after we get results
                    //make the element checked
                    $this.attr('checked', checked); 
                },
                error:function(){
                    //make the element unchecked
                    $this.attr('checked', !checked);                    }
            });
    });
});

I think you can reduce it to something like this:

 $(document).ready(function($) { // if any checkbox changes, this is the handler for it $("input[type='checkbox']").change(function() { var checkboxIsChecked = $(this).is(":checked"); var strStat = (checkboxIsChecked) ? "1" : "0"; $.ajax({ url: 'code.php', type: 'POST', data: { db_column: $(this).attr("name"), strState: strStat, user: "admin" }, success: function() { // this happens after we get results console.log('SUCCESS'); $(this).attr('checked', true); }, error: function() { console.log('ERROR'); $(this).attr('checked', false); } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="rep_label"> <input type="checkbox" id="goal1admin" name="goal1hit" value="1" checked />This is my first goal</label> <label class="rep_label"> <input type="checkbox" id="goal2admin" name="goal2hit" value="1" />Goal 2</label> <label class="rep_label"> <input type="checkbox" id="goal3admin" name="goal3hit" value="1" checked />3rd time is the charm</label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM