Break loop on page

Asked

Viewed 118 times

0

I have a problem, that I researched and thought how to do, but I could not solve. I have a select on the page that needs to be populated after a condition is met. And after that, it needs to query the data relating to the option chosen in select. Suppose this select is to fill in the user name, and after it is filled in, a query should be made in the database with the data relating to that user. And that’s where my problem is, although I can fill in the select and bring the data related to the chosen user, every time the page starts, the script runs again and all the time. It’s kind of like a query loop that I can’t stop. How can I make it just a query and after that, he interrupts so that the query is not made again?

It’s more of a logic problem than a syntax problem, which is why I reduced the code itself.

    <script>
$(document).ready(function () {
    if (condicao) {
        $.ajax({
            // execução do ajax, aqui preencho o select
        });
        // aqui está o problema, ao preencher o select, é para submeter o form. Porém isso tem causado loop na consulta
    }
    })
    </script>

    <form method="post">
    <select class='form-control' id='opcoes'>
    </select>
    </form>
  • What returns in ajax?

  • that ajax, returns data in json format, with which I fill the select. After that, I need to submit the form, and that’s my problem, I don’t know where I can put this form to consult without it loop with it

  • everything happens the way I want, except this loop

  • At first you can solve it by creating a flag (true/false) in the session, where when the ajax operation is performed, in the controller you change the flag to false. In JS, you can recover a session variable using "${flag}".

  • well thought out, a session variable in javascript itself...

1 answer

1

Good, come on. From what I understand. After filling the select, you would like to send the form, but it continues in a loop the Ajax, right?!

What you can do to solve this is to create a "lock" variable and fill it in the ajax Success. I will try to give an example:

    var stop = false;
<script>
$(document).ready(function () {
if (condicao) {
    if(!stop){
        $.ajax({
          method: "POST",
          url: "some.php",
          data: { name: "John", location: "Boston" }
        }).done(function() {
            stop = true;
          });
    }
    }
})
</script>

<form method="post">
<select class='form-control' id='opcoes'>
</select>
</form>

Here are some examples of using functions at the end of ajax: http://api.jquery.com/jquery.ajax/#entry-examples

I hope it helped. Hugs

Browser other questions tagged

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