How do I send my form along with another variable via AJAX POST to PHP?

Asked

Viewed 1,077 times

2

Then, I have a form and send his data to a PHP file via AJAX. I’m doing this normally.

Only now I had the need to send along with the form, plus a Javascript variable from AJAX to PHP. To use the value of this variable as a condition in PHP.

It seems to be a very simple thing, but I’m only seeing amazing solutions on the web. If you can help me, I would be grateful.

Below is my Javascript code and a part of the PHP Code:

$('#resultados-pendentes').click(function(e) {
    e.preventDefault();
    var formularioPendente = $("#formulario-consulta");
    var pendente = "PENDENTE";

    var retorno = inserirFormulario(formularioPendente, pendente);

}); 

   

function inserirFormulario(dados, condicao) {
    $.ajax({
        //dataType: "json",
        type: "POST",
        data: dados.serialize(), //Aqui eu gostaria de enviar minha variável
        url: "banco/pagina-minhas-tarefas/interface-resultado-pesquisa.php",
        cache: false,

    });
}
<?php

 <!-- Arquivo PHP QUE RECEBE OS DADOS DO FORMULÁRIO (SÓ UMA PARTE DO CÓDIGO) -->

  <?php 

	require_once("../conexao/conexao-com-banco.php"); // CHAMANDO O ARQUIVO DE CONEXÃO AO BANCO

	
		
	// CONSULTA GERAL DO BANCO  QUE RETORNA O RESULTADO DA CONSULTA DA PÁGINA INTERFACE.PHP 
		
	session_start();	
	
			
			//PREENCHE AS VARIÁVEIS COM OS DADOS VINDOS DOS CAMPOS DO FORMULÁRIO
			$pegaropcao   = $_POST["prioridade"];
			$tipodedata = $_POST["data"];
			$dataInicial = !empty($_POST["dataInicial"]) ? $_POST["dataInicial"] : null;
			$dataFinal  = !empty($_POST["dataFinal"]) ? $_POST["dataFinal"] : null;
			$cod = $_POST["cod"];
			$empresas   = !empty($_POST["empresas"]) ? $_POST["empresas"] : "";
			$tributacao = !empty($_POST["tributacao"]) ? $_POST["tributacao"] : "";
			$atividade  = !empty($_POST["atividade"]) ? $_POST["atividade"] : "";
			
			
			$status = $_POST["status"];
			$responsavel = $_SESSION["nome"];


?>

If I just put the variable name there after the comma where I’m sending the form it goes along with the form ? (I mean, on the date).

Thank you!

3 answers

2


I believe that the simplest solution is to continue using the facility that serialize() offers in a form, can create a <input type="hidden" id="pendente" name="seu-name" > and put the information you need on it $('#pendente').val(pendente), thus the function serialize() will read this field.

An input of the kind hidden does not appear to the user.

After placing the <input type="hidden" id="pendente" name="seu-name" > within your HTML form just change the following part of your code:

$('#resultados-pendentes').click(function(e) {
    e.preventDefault();
    var formularioPendente = $("#formulario-consulta");
    var pendente = "PENDENTE";
    $('#pendente').val(pendente); // Se esse valor da variável pendente vai mudar...
    var retorno = inserirFormulario(formularioPendente, pendente);

});

Don’t forget to put the attribute name with the name your code awaits.

  • 1

    That’s what I would do too, JS updates the field hidden. This way the form is sent without interference from the JS.

  • Worth a vote then right? D

  • Yes, but this input type="Hidden" option would not be useful for me. Because I send the form in other ways than Submit. For example, there is a <div> that when I click on it, I send the form data as well. and the value of this input type="Hidden" could not be fixed.

  • So it’s not just adding a field, it can be several fields and different names?

  • It will not be fixed... you will set it in JS... if it depends on another field that you will set in your code.

  • @Thiagopetherson, inside of $('#pendente').val(var) var would be your variable.

  • @fernandosavio , I would just like to have a variable that sends a value to be a condition in the php file. Only this value can vary. Understand ? Laércio, I’m analyzing your code and seeing how I can adapt it to mine.

  • See the edited response if it helps.

  • 1

    @Laérciolopes , your code was useful to me. Now I will make some adaptations here. Thank you! It served me momentarily. The only however is how I would send, via AJAX, that variable "pending" along with the form for the PHP file.

  • Thanks @Thiagopetherson!

  • That’s exactly what my answer is explaining, putting the input into the HTML form it will be read by the function serialize(), just put the correct name attribute and receive this parameter in the PHP file. HTML example: <input type="hidden" name="test" id="pendente"> PHP: $_POST['test']

Show 6 more comments

1

You can use a FormData to serialize the form and enter new data before sending by ajax (example of use with ajax).

It is important to check the functionality compatibility if using Formdata (MDN, Caniuse).

let form = document.getElementById('form')

// Inicializa com os dados do Form
let formData = new FormData(form)

// Adiciona mais um valor aos dados
formData.append("campo4", "Valor 4")

$.ajax({
    url: "https://httpbin.org/post",
    type: 'post',
    data: formData,
    processData: false,
    contentType: false,
}).then(response => console.log("- Dados enviados", response.form));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form">
  <input name="campo1" value="Valor 1">
  <input name="campo2" value="Valor 2">
  <input name="campo3" value="Valor 3">
</form>

0

When you use jQuery and give a serialize() in a form, what jQuery is doing is turning this object into a query Parameters, that looks like this: nome=Thiago&idade=99.

If you want to add one more parameter, just concatenate it in your string keeping the same pattern: &variavelExtra=texto-da-variavel.

You just need to be careful with the encounter, that you can solve with encodeURIComponent().

The end result could be something like this:

dados.serialize() + '&variavel=' + encodeURIComponent(variavelComValor)
  • Thiago R, the '$variable' would be the one sent via POST to PHP ? That is, in the PHP file, which receives what comes from AJAX, would be $_POTS['variavel'] ?

  • It didn’t work for me, Thiago R.

  • How’s your code in this part of the shipment?

  • Thiago R, I was able to solve briefly with Laércio’s solution. But still, thank you!

Browser other questions tagged

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