Script making too many wrong requests

4

I am in the following dilemma, which may be simple for many here, however, as I am a beginner, I am experiencing a major difficulty in a system I am supporting ...

When you click a button, you run a script that returns data in JSON. However, with each click, it is as if it folds the execution of this script (Execute 2x, then runs 4, 8, 16, etc.).

You who have more experience in the area, can you give me a light, please?

I am sending the 2 script functions, in case the two are in some conflict, and the requested PHP file.

selectDB

functionselectDB(){$(document).ready(function(){varpos=document.getElementById('dgn_id').value;varpostURL="busca_dgn_pri.php";
    $.ajax({
            async: false,
            type: "POST",
            cache: 'false',
            url: postURL,
            data: {dgn_id: pos},
            success: function(html){
                var dgnData = $.parseJSON(html);

                $('#dgn_pri')
                .append($("<option></option>")
                .attr("value",dgnData.dgn[0].dgn_pri)
                .attr("selected","selected")
                .attr("disabled","disabled")
                .text(dgnData.dgn[0].dgn_pri));
            }
    });
    });
}

addOptionSelect

 function addOptionSelect(){
    $(document).ready(function () {
        $("option").remove();

        $('#btnprox').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btnante').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btnprim').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btnulti').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btnnovo').click(function(){
            $("option").remove();
            addOptionSelect();
        });
        $('#btnexcl').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btncanc').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });
        $('#btnsalv').click(function(){
            $("option").remove();
            addOptionSelect();
            selectDB();
        });

        var sel = $('input[type=checkbox]:checked').map(function(_, campo) {
            var nomeCampo = $(campo).attr('name');
            return nomeCampo;
        }).get();

        $.each(sel, function(key, value){
            if (($('option[value='+key+']').length == 0) && (value != "sem_diag")) {
                var campoTxt = $('label[for='+value+']').html();
                $('#dgn_pri')
                    .append($("<option></option>")
                    .attr("value",campoTxt)
                    .text(campoTxt));                
            } else {
                $("option").remove();
            }
        });

    });
}

PHP file

    $pos = $_REQUEST['dgn_id'];

$sql = "SELECT dgn_id, dgn_pri FROM nut_diagnutric WHERE dgn_id = $pos";

$result = $DB->query($sql);

$rows = array();
while($row = $DB->fetchArray($result)){
        $rows[] = $row;
}

$qryResult = array();
$qryResult['dgn'] = array_unique($rows);
echo json_encode($qryResult);
    
asked by anonymous 04.08.2015 / 21:51

4 answers

4

Within the function call to itself I believe that this is the root of the problem, because every time you click, another event is made, and the next time the mouse is pressed it triggers 2 events (or more according for incrementing) in parallel:

function addOptionSelect(){
.
.
.
    addOptionSelect();
}

Then every time she calls herself, she "prepares" another click () event or the click event propagates by generating all of these events.

To fix quickly you can send a stopimmediatepropagation () within the click () event like this:

$('#btnnovo').click(function(e){
...
e.stopimmediatepropagation();
....
});
  

link

Another thing I would comment on is $(document).ready(function () { but it has already been commented on, so just look at that detail too, but in the case in question there will be no effects. (although it is wrong to use it the way it is)

    
04.08.2015 / 22:02
5

If I understand correctly your code can be summed up to this:

$(document).ready(function () {
    $('#btnprox,#btnante,#btnprim,#btnulti,#btnnovo,#btnexcl,#btncanc,#btnsalv').click(function(){
        $("option").remove();
        addOptionSelect();
        selectDB();
    });

    function addOptionSelect(){   
        var sel = $('input[type=checkbox]:checked').map(function(_, campo) {
            var nomeCampo = $(campo).attr('name');
            return nomeCampo;
        }).get();

        $.each(sel, function(key, value){
            if (($('option[value='+key+']').length == 0) && (value != "sem_diag")) {
                var campoTxt = $('label[for='+value+']').html();
                $('#dgn_pri')
                    .append($("<option></option>")
                    .attr("value",campoTxt)
                    .text(campoTxt));                
            } else {
                $("option").remove();
            }
        });
    }

    function selectDB(){
        var pos = document.getElementById('dgn_id').value;
        var postURL= "busca_dgn_pri.php";
        $.ajax({
                async: false,
                type: "POST",
                cache: 'false',
                url: postURL,
                data: {dgn_id: pos},
                success: function(html){
                    var dgnData = $.parseJSON(html);

                    $('#dgn_pri')
                    .append($("<option></option>")
                    .attr("value",dgnData.dgn[0].dgn_pri)
                    .attr("selected","selected")
                    .attr("disabled","disabled")
                    .text(dgnData.dgn[0].dgn_pri));
                }
        });
    }
});
    
04.08.2015 / 22:09
4

You have some ideas in the code that are wrong and / or may be the source of the problem.

In general, when adding new elements to the DOM, you must add event handlers to your own element (s). If you are going to use a generic selector type $('.minhaClasse') and there are elements already on the page with this class that already have an event handler, then you will have code to run twice.

Another thing that does not make much sense in your code is to have the addOptionSelect function call itself when what it does is add event handlers. This is guaranteed to add duplicate event handlers, and have code running twice.

Another thing that does not make much sense is that you have $(document).ready(function () { within that function. You have a logic problem. This $(document).ready(function () { must be run once at the top of the page load, if necessary, and not more.

    
04.08.2015 / 22:00
4

Your problem is in how you created the function addOptionSelect

To understand more simply I simplified its function to the minimum necessary for the problem to occur, excluding only the code that calls addOptionSelect for the first time

function addOptionSelect() {
    $(document).ready(function () {

        //$("option").remove();

        $("#btnprox").click(function () {
            addOptionSelect();
            console.log("click do btnprox");
        });

        console.log("resto do código");
    });
}

With just this, the first time I click the btnprox button it performs as expected and the message appears once, but in the next clicks it doubles the amount of messages.

This is because at the click of the button you call the addOptionSelect function again, and this function adds a new handler to the button click, so the next time you click the button this code is executed 2 times, adding 2 more handler for the click, which next time executes 4 times, added 4 more handlers for the click and so on.

What you need to do is remove the code that adds the handlers from within this function and execute it only once when the page loads, such as

function addOptionSelect() {
    $(document).ready(function () {

        //$("option").remove();

        console.log("resto do código");
    });
}

$(document).ready(function() {
    $("#btnprox").click(function () {
        addOptionSelect();
        console.log("click do btnprox");
    }); 
});
  

Note that $(document).ready is not really needed within addOptionSelect , I just included it in the example to make the code more similar to the original and make it easier to understand the difference

    
04.08.2015 / 22:29