How to make an AJAX call through the post

Asked

Viewed 41 times

0

Hello I have a field on the site called search service, and would like to make an ajax call to redirect to another page.

  <li>
        <form class="navbar-form full-width">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Buscar Atendimento..." />
                <button id="Busca"  type="submit" class="btn btn-search"><i class="fa fa-search"></i></button>
            </div>
        </form>
    </li>

Function:

  function FiltrarRelatorio() {

        var Busca = $('#Busca').val();

        if (remover === true) {
            Busca = 0;
        }


        $.ajax({
            type: "post",
             url: '@Url.Action("Agendamentos")',
            data: {
                Busca: Busca
            },
            success: function (data) {
                window.location.href = data;
            },
            error: function () {


            },
            complete: function () {

                //location.reload();

            }


        });
    }

What am I doing wrong? When I click on the button it just reloads the source page instead of going to the destination page.

  • Where does this variable come from remover in if (remover === true) { and why the variable Busca must be equal to 0? Where you are calling the function FiltrarRelatorio() to execute the Ajax?

  • Because you’re getting the value of the button in $('#Busca').val()? You shouldn’t take the input value?

2 answers

1

Tiago, you are recovering the value of the button instead of the value of your field. Set an id in your input, for example:

And there replace in its function: var Search = $("#txtBuscar"). val();

0


In no time are you calling the function FiltrarRelatorio and is just submitting the form to the page itself, causing it to reload.

What you have to do is cancel the form Submit and call the function FiltrarRelatorio, and take the value of the input and not the button. Put the id #Busca in the input, not in the button and do the following:

// captura o submit do formulário e chama  a função
$("form").submit(FiltrarRelatorio);

function FiltrarRelatorio(event) {
   event.preventDefault(); // cancela o submit

   var Busca = $('#Busca').val();

   $.ajax({
      type: "post",
      url: '@Url.Action("Agendamentos")',
      data: {
         Busca: Busca
      },
      success: function (data) {
         window.location.href = data;
      },
      error: function () {
      },
      complete: function () {

         //location.reload();

      }
   });

}

Browser other questions tagged

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