How to send several variables to another page and return in a div (Jquery)?

Asked

Viewed 489 times

3

I’m trying to send data from a form to another page, and bring from it a chart in a div with id="return", which is below the form.

The form has the code, data1, data2 and store, but it seems that the variables are not being sent correctly.

I’ve done something similar but only with one variable, but with several like.

My job jQuery is down, I believe there’s something wrong with it.

I found several examples on the internet, but none helped me and solved my problem.

  $(document).ready(function() {

    //alert("teste 1 ");

    /// Quando usuário clicar no botão será feito todos os passo abaixo
        $('#formulario').submit(function() {

        //alert("teste 2");

            var codigo = $('#codigo').val();
            var data1 = $('#data1').val();
            var data2 = $('#data2').val();
            var loja = $('#loja').val();

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'retorna_produto.php',
                async: true,
                data: {codigo, data1, data2, loja},
                //data: {'codigo='+ $('#codigo').val(),
                //  'data1='+ $('#data1').val(),
                //  'data2='+ $('#data2').val(),
                //  'loja='+ $('#loja').val()
                //},
                success: function(data) {
                     $('#retorno').html(data);
                }
            });

            return false;
        }); 
    });

1 answer

0


The form has the code, data1, data2 and store, but it seems that the variables are not being sent correctly.

Check if the identification selectors are in agreement.

You can simplify the collection of the form information using serialize. an example of this would be:

$('#formulario').submit(function(e) {
  e.preventDefault();
  var dados = $(this).serialize();
  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: 'retorna_produto.php',
    data: dados,
    success: function(data) {
      $('#retorno').html(data);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<form id="formulario">
  <input type="text" name="codigo" value="1">
  <input type="text" name="data1" value="valor data 1">
  <input type="text" name="data2" value="valor data 2">
  <input type="text" name="loja" value="Loja 1">
  <button>
    Enviar Formulario
  </button>
</form>

This way you can pass a queryString to the ajax date parameter and send.

Another thing, in the Ubmit method it is recommended to use the preventDefault() instead of Return false to prevent the page from being reloaded.

  • I’ll test it, thank you.

  • It worked, thanks, the only thing I changed was dataType: 'json', which I had to put dataType: 'html', otherwise it wouldn’t work.

Browser other questions tagged

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