Script making many improper requests

Asked

Viewed 243 times

4

I am in the following dilemma, which may be simple for many here, but as a beginner, I am going through a great difficulty in a system that I am supporting...

By clicking a button, a script which returns data in JSON. However, with each click, it is as if it doubles the execution of this script (Runs 2x, then runs 4, 8, 16, etc).

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

I’m sending the 2 functions of the script, in case the 2 are in some conflict, and the PHP file requested.

Várias Requisições

selectDB

    function selectDB(){
    $(document).ready(function(){
        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));
            }
    });
    });
}

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);
  • Put the parameter event (the function should be function(event)) in each function of events also put the following code event.preventDefault(); and event.stopPropagation(); at the beginning of each click event that is called the function selectDB(). See if it solves.

  • Put pf more information than JSON has and what you want to do with the data coming from PHP so we can help more.

  • This function Function selectDB(){ .. } does not need a subfunction : $(Document). ready(Function(){}); because this is only used to load when reading the document, you can pass all the contents of that ready Ocument within its direct method... otherwise it will be reading several times this post.

4 answers

5

If I understand your code correctly it 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));
                }
        });
    }
});

4

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

In general when you add new elements to the DOM you should add Event handlers to the proper(s) element(s). If you’re gonna use a generic selector like $('.minhaClasse') and there are already elements on the page with that class and that already have an Event Handler, so you will have code running twice.

Another thing that doesn’t make much sense in your code is to have the function addOptionSelect to call herself herself when all she does is add Event handlers. This is guaranteed to add duplicate handlers, and have code running twice.

Another thing that doesn’t make much sense is that you $(document).ready(function () { within that function. You have a logic problem. That $(document).ready(function () { should be run once at the beginning of the page load, if necessary, and no more.

4


Inside the function has call to itself I believe that this is the root of the problem, because every time you click, another event is done, and the next time the mouse is pressed triggers 2 events( or more as incremented) in parallel:

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

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

To quickly correct you can have a stopimmediatepropagation() inside the click() event like this:

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

http://api.jquery.com/event.stopimmediatepropagation/

Another thing I’d like to comment on is $(document).ready(function () { but it has already been commented, so just pay attention to that detail as well, but in the case in question there will be no effects. (although it is wrong to use it the way in which this)

4

Your problem is in how you created the function addOptionSelect

To understand more simply I have 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 that, the first time I click the button btnprox it performs as expected and appears once the message, but in the following clicks it doubles the number of messages.

This is because at the click of the button you re-call the addOptionSelect function, and this function adds a new Handler to the click of the button, so the next time you click this code runs 2 times, adding 2 more Handler to the click, that next time runs 4 times, added 4 more handlers to the click and so on.

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

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");
    }); 
});

Obs, the $(document).ready is not really necessary within the 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.