php – How to send several variables to another page and return in a div (JQuery)?

Question:

I'm trying to send data from a form to another page, and bring from it a graphic 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 like this but only with one variable, but not with several like that.

My jQuery function is below, I believe there is something wrong with it.

I found several examples on the internet, but none of them 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;
        }); 
    });

Answer:

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 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 data parameter and send.

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

Scroll to Top