javascriptajaxcallbackcontent-management-system

Exiting a callback function


I would like to ask how to exit the callback function given below before ajax call if valueid2 equals 0

callback: function() {
                        console.log('save');
                        console.log($('#re_confirm')[0].checked);
                        var valueid = document.getElementById('idtable').value
                        if(valueid == 0)
                           myFunction();
                        var valueid2 = document.getElementById('idtable').value

                         $.ajax({
                            url : "<?php echo base_url(); ?>index.php/home/update_booking",
                            type: "post",
                            data: {
                                "table_id" : $('#idtable').val(),
                            },
                            success: function(response){
                                   ...
                            }
                       });
      }

Please tell me how to exit the callback function.


Solution

  • You can do it by simply using return. This will return the function if valueid2 is 0, and the ajax call will not be run:

    callback: function() {
        console.log('save');
        console.log($('#re_confirm')[0].checked);
        var valueid = document.getElementById('idtable').value
        if(valueid == 0)
            myFunction();
        var valueid2 = document.getElementById('idtable').value
    
        if (valueid2 == 0) {
            return; // This return here will end the function
        }
    
        $.ajax({
        url : "<?php echo base_url(); ?>index.php/home/update_booking",
        type: "post",
        data: {
            "table_id" : $('#idtable').val(),
        },
        success: function(response){
            ...
        }
        });
    }