Send form data via GET to server (without updating page)

Asked

Viewed 3,812 times

3

I have this form and would like to give a GET for variables with their value when clicking the button, without refreshing the page because I have other forms on the same page, it is possible with PHP, or have to use AJAX ?

Form layout

Formulario

HTML

<div class="form-group">
  <div class="col-sm-7">
    <label for="inputEmail3" class="control-label" contenteditable="true">
      Espaçamento entre linhas(metros):
    </label>
  </div>
  <div class="col-sm-10">
    <input type="text" class="input-mini" placeholder="1" id="linhas" value="1" disabled>
  </div>
</div>

<div class="form-group">
  <div class="col-sm-7">
    <label for="inputPassword3" class="control-label">
      Espaçamento entre plantas(metros):
    </label>
  </div>
  <div class="col-sm-10">
    <input type="text" class="input-mini" id="plantas" placeholder="1" value="1" disabled>
  </div>
</div>

<div class="form-group">
  <div class="col-sm-6">
    <label for="inputPassword3" class="control-label">
      Tamanho da área a ser plantada:
    </label>
  </div>         
  <div class="col-sm-10">
    <p>
      <input type="text" class="input-mini" id="tamanho">
      <select class="selectpicker">
        <option>ha</option>
        <option>m²</option>
      </select>
    </p>        
  </div>
</div>

<div class="form-group">
  <div class="col-sm-offset-2 col-sm-10">
    <div class="checkbox">
      <label>
        <button type="submit" class="btn btn-default">Estimar</button>
      </label>
    </div>
  </div>
</div>
</form>
  • 1

    Want to reload the page when you click on Estomar or want to send this data to PHP without refreshing the page? (Also put your HTML please)

  • I don’t think I expressed myself well, I will edit the post. Obg

  • Unless this is in an iframe you will need AJAX. Which prefer?

  • I prefer AJAX, because I don’t know how to work with Iframe,

  • 1

    And use Mootools, jQuery or another library or it has to be pure Javascript?

  • The only framework I’m using is bootstrap, it might be jquery yes, no problem

Show 1 more comment

2 answers

5

By making use of an AJAX call using jQuery to facilitate our work, we can handle the issue by making use of the function $.ajax() as follows:

var dadosFormulario = $("#formulario").serialize();

$.ajax({
  type: "GET",
  url: "caminho/para/ficheiro.php",
  data: dadosFormulario,
  success: function(resposta) {
    // variável "resposta" contém o que o servidor envia
    // aqui código a executar quando correu tudo bem
  },
  error: function() {
    // correu mal, agir em conformidade
  }
});

Or the same code in a more portable form where for this purpose the HTML should be perfectly valid:

var $form = $("#meuFormulario");

$.ajax({
  type: $form.attr("method"),  // GET ou POST definido no atributo "method" do formulário
  url: $form.attr("action"),   // URL para onde enviar os dados definido no atributo "action"
  data: $form.serialize(),
  success: function(resposta) {
    // variável "resposta" contém o que o servidor envia
    // aqui código a executar quando correu tudo bem
  },
  error: function() {
    // correu mal, agir em conformidade
  }
});

In detail

In order to be able to make use of such a solution, you should take into account a few things:

  1. Form should preferably contain an attribute ID to uniquely identify you on the page:

    <form id="meuFormulario" method="GET" action="http://www.meusite.com/ficheiro.php">
      <!-- ... -->
    </form>
    
  2. If the AJAX call code will be executed by clicking on a button of type submit or in a link, through the method .on(), .click() or other such, we must avoid the normal behavior of these elements so that the page is not submitted to the server and/or updated:

    $('#meuBotao').on("click", function(e) {
      e.preventDefault();
      // chamada AJAX aqui
    });
    

    or if we are performing the AJAX call directly in the form submission, using the .submit() the concept is the same:

    $('#meuFormulario').submit(function(e) {
      e.preventDefault();
      // chamada AJAX aqui
    });
    
  3. The elements on the form, to follow with a $_GET or $_POST must all contain an attribute name whose same is what will allow them to be identified by the server and thus collect their values:

    <input type="text" name="meuNome" value="">
    

    Note that these names are unique identifiers, with some exceptions when the goal is to create an array of results or as in the case of radio where only one value is returned from a set of them.

  4. In the file .php where AJAX will send the GET, You can catch the same as follows:

    if (isset($_GET) && is_array($_GET)) {
      $meuNome = $_GET["meuNome"];
    }
    else {
      echo 'Ups... Preciso receber um GET e o mesmo deverá conter dados!';
    }
    

0

Use $('form').serialize(); or $('form').serializeArray();

  • 1

    When there is such a response, it is advisable to explain why using these functions solves the problem.

Browser other questions tagged

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