Send variables via GET by php Ajax

Asked

Viewed 1,918 times

0

I am creating a page in PHP that makes a query in a JSON/PHP via ajax and I need it to send to the URL, the form variables so I can make a query in this JSON/PHP.

HTML:

    <form method="GET" name="formularioBusca"> <input type="text" id="from-airport" name="Origem" class="form-control" placeholder="Onde você esta?"  autocomplete="off" required="required">
<input type="text" id="to-airport" name="Destino" class="form-control" placeholder="Para onde você quer ir?" autocomplete="off" required="required">
<button class="btn btn-buscar-voos" id="buscarVoos" >BUSCAR VOOS</button></form>

Javascript:

    $(document).ready(function(){$('#from-airport').blur(function(){
    $('#buscarVoos').on('click', function(e){
        $('#from-airport').blur(function(){
            var partida = $(this).val();
            var palavras = partida.split(' ');
            var origem = [palavras.pop()];
            sigla = origem.toString().replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
            console.log(sigla);
        })
        $('#to-airport').blur(function(){
            var destino = $(this).val();
            var saida = destino.split(' ');
            var origem = [saida.pop()];
            siglaDestino = origem.toString().replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
            console.log(siglaDestino);
        })
    $.ajax({
                  url: 'api.php',
                  type: 'GET',
                  dataType: 'html'
                })
                .done(function(data){
                  console.log(data);  
                  $('#dynamic-content').html('');    
                  $('#exibeVoos').html(data); 
                  $('#modal-loader').hide(); 
                })
                .fail(function(){
                  $('#dynamic-content').html('<i class="glyphicon glyphicon-info-sign"></i> Aguarde...');
                  $('#modal-loader').hide();
                });
    })
})
  • It is necessary to create a button or check that both fields are filled. The way you’re doing, you’re sending the data before it’s even filled out.

  • Oh yes, I forgot to ask the question, $('#buscarVoos'). on('click', Function(e){.. ..... })

  • If possible click on [Edit] and change your code if necessary.

  • I changed, Thank you! =)

1 answer

1

To send data with jQuery.ajax, simply enter the attribute data configuration. This attribute will contain the information that should be sent, either via POST, or GET, for example:

$.ajax({
    url: 'api.php',
    type: 'GET',
    dataType: 'html',
    data: $("form[name=\"formularioBusca\"]").serialize()
})

The $(elemento).serialize(); serves to capture and convert (to default application/www-url-encoded), all the form fields.

In HTML, you need to add the attribute type="button" to the button element. This will cause the client not to be redirected by clicking on it.

Html:

<form method="GET" name="formularioBusca">
    <input type="text" id="from-airport" name="Origem" class="form-control" placeholder="Onde você esta?"  autocomplete="off" required="required">
    <input type="text" id="to-airport" name="Destino" class="form-control" placeholder="Para onde você quer ir?" autocomplete="off" required="required">

    <button type="button" class="btn btn-buscar-voos" id="buscarVoos" >BUSCAR VOOS</button>
</form>

Javascript:

$(document).ready(function() {

    const URL_SEARCH = new URL(location.href);

    $("from-airport").val( URL_SEARCH.searchParams.get("Origem") );
    $("to-airport").val( URL_SEARCH.searchParams.get("Destino") );

    $('#from-airport').blur(function() {
        let partida = $(this).val();
        let palavras = partida.split(' ');
        let origem = [palavras.pop()];
        sigla = origem.toString().replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");

        console.log(sigla);
    })
    $('#to-airport').blur(function() {
        let destino = $(this).val();
        let saida = destino.split(' ');
        let origem = [saida.pop()];
        siglaDestino = origem.toString().replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");

        console.log(siglaDestino);
    })

    $('#buscarVoos').on('click', function(e) {

        history.pushState(null, null, "?" + $("form[name=\"formularioBusca\"]").serialize())

        $.ajax({
            url: 'api.php',
            type: 'GET',
            dataType: 'html',
            data: $("form[name=\"formularioBusca\"]").serialize()
        })
        .done(function(data) {
            console.log(data);
            $('#dynamic-content').html('');
            $('#exibeVoos').html(data);
            $('#modal-loader').hide();
        })
        .fail(function() {
            $('#dynamic-content').html('<i class="glyphicon glyphicon-info-sign"></i> Aguarde...');
            $('#modal-loader').hide();
        });
    })
})

In this way, your request will be sent to: http://www.YOUR-SITE.com/api.php?Origem=teste-origem&Destino=teste-destino, but the user will not see this request.

If you want to change the URL as well (and without redirecting), just use the history.pushState, for example:

history.pushState(null, null, "?" + $("form[name=\"formularioBusca\"]").serialize())

And to capture the user URL and fill in your form, just use the API URL

If your form contains an upload field, I recommend /a/279834/99718.

  • Thanks for the help, but it’s not generating the URL every time I click "SEARCH"with the parameters, and my form has no upload field

  • @Cristianofacirolli jQuery will do this automatically, but if this is really necessary... I edited my answer answering this question.

  • I understand, but every time you click on the button you need to generate a URL with the parameters that have been filled in like this image https://prnt.sc/ipbws3

  • @Cristianofacirolli The parameters are generated, only it is not shown to the user (this is one of the functions of jQuery.ajax), otherwise simply remove the event click button and add attribute action="api.php" in the element form

  • I need to generate a URL because the user can make future queries directly.

  • @Cristianofacirolli I edited my answer. Your case fits the last example.

  • I got it, in case it gives a GET to the api.php file, only it can’t send it, the api.php file has to work on the same page of the form, below it. The api.php file does the query and returns in form.php

  • @Cristianofacirolli edited my answer

  • I’m sorry my inexperience but he’s asking that there is no variable URL in the line const URL = new URL(Location.href);

  • @Cristianofacirolli Sorry for the error. Fix the code.

  • That’s exactly what it was, thank you so much for your help! I’ll study more on the subject! =)

  • @Cristianofacirolli If possible mark as solved, so other users can more easily view the answer during a search.

Show 7 more comments

Browser other questions tagged

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