I'm trying to send data from a form to a PHP page, via AJAX, but I'm not sure if I'm doing it correctly, because I'm not able to echo these variables.
Here is the code of the page containing the form (some information has been hidden, but the code is working):
<body>
<div class="container">
<div class="row">
<div class="mt-5 col-12 col-md-12 col-lg-12">
<form id="adicionar_funcionario" method="POST" enctype="multipart/form-data" class="p-md-5">
<h2 class="text-center"><?php echo $titulo; ?></h2>
<div style="float: left;" class="mt-5">
<img src="../img/avatar.png" alt="Selecione uma imagem" <?php if(isset($errofoto)){echo "class='invalidoimg imgupload'";}else{echo "class='imgupload'";}?> id="imgfoto">
<img src="../img/lixeira.png" id="lixeira" alt="Limpar foto" class="lixeira">
<span class="erro"><?php if(isset($errofoto)){echo $errofoto;}?></span>
</div>
<div class="row mt-5">
<div class="ms-2 ms-lg-5 text-center col-5 col-lg-1 col-md-2 col-sm-2">
<!-- SITUA?�??O -->
<label for="situacao"> Situa?�??o: </label>
</div>
<div class="col-7 col-lg-2 col-md-4 col-sm-4">
<div class="form-check form-switch">
<input id="situacao" name="situacao" class="form-check-input" type="checkbox" value="1" onclick="mudarlabel(this.checked)" <?php if(isset($situacao)){echo "checked";}else{echo "checked";} ?>>
<label class="form-check-label" for="situacao" id="labelsituacao"><?php if(isset($situacao)){echo "Ativado";}else{echo "Ativado";} ?></label>
</div>
</div>
</div>
<div class="ms-lg-5 mt-4 col-12 col-md-12 col-lg-12">
<div class="row">
<div class="ms-lg-5 col-12 col-lg-4 col-md-4 col-sm-4">
<!-- PRONOME -->
<label for="pronome"> Pronome </label>
<select id="pronome" <?php if(isset($erropronome)){echo "class='invalido form-select'";}else{echo "class='form-select'";}?> <?php if (isset($_POST['pronome'])){echo "value='".$_POST['pronome']."'";}?> name="pronome">
<?php
if ((isset($_POST['pronome']))){
?>
<option selected><?php echo $_POST['pronome'];?></option>
<?php
}else{
?>
<option selected>Selecione uma op?�??o</option>
<?php
};
?>
<option value="Ele/Dele">Ele/Dele</option>
<option value="Ela/Dela">Ela/Dela</option>
<option value="Todos">Todos</option>
</select>
<span class="erro"><?php if(isset($erropronome)){echo $erropronome;}?></span>
</div>
<div class="col-12 col-lg-4 col-md-4 col-sm-4">
<!-- NOME COMPLETO -->
<label for="nomecompleto"> Nome completo </label>
<input type="text" id="nomecompleto" placeholder="Como consta no CPF..."<?php if(isset($erronomecompleto)){echo "class='invalido form-control'";}else{echo "class='form-control'";}?> <?php if (isset($_POST['nomecompleto'])){echo "value='".$_POST['nomecompleto']."'";}?> name="nomecompleto">
<span id="erronomecompleto" class="erro"><?php if(isset($erronomecompleto)){echo $erronomecompleto;}?></span>
</div>
</div>
</div>
<div class="ms-lg-5 mt-4 col-12 col-md-12 col-lg-12">
<div class="row">
<div class="ms-lg-5 col-12 col-lg-4 col-md-3 col-sm-4">
<!-- NOME SOCIAL -->
<label for="nomesocial"> Nome social </label>
<input type="text" id="nomesocial" placeholder="Gostaria de ser chamado(a)..." <?php if(isset($erronomesocial)){echo "class='invalido form-control'";}else{echo "class='form-control'";}?> <?php if (isset($_POST['nomesocial'])){echo "value='".$_POST['nomesocial']."'";}?> name="nomesocial">
<span class="erro"><?php if(isset($erronomesocial)){echo $erronomesocial;}?></span>
</div>
<div class="col-12 col-lg-4 col-md-3 col-sm-4">
<!-- NOME -->
<label for="nomeartistico"> Nome Art?�stico </label>
<input type="text" id="nomeartistico" placeholder="Ir?? aparecer nos cr?�ditos..." <?php if(isset($erronomeartistico)){echo "class='invalido form-control'";}else{echo "class='form-control'";}?> <?php if (isset($_POST['nomeartistico'])){echo "value='".$_POST['nomeartistico']."'";}?> name="nomeartistico">
<span class="erro"><?php if(isset($erronomeartistico)){echo $erronomeartistico;}?></span>
</div>
</div>
</div>
<input accept="image/png,image/jpeg,image/jpg" type="file" id="foto" name="foto">
<input type="text" id="removerfoto" name="removerfoto">
<div class="form-group text-center">
<button id="criar" type="submit" class="mt-5 botao">Criar</button>
</div>
</div>
<!-- Modal -->
<div class="modal hide fade" id="anexar_documentos" tabindex="-1" role="dialog" aria-labelledby="Documentacao" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="TituloModalLongoExemplo">Anexar documentos</h3>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<h6 class="ms-3 mt-2"><b><i>Os arquivos precisam ser no formato jpg, png ou pdf e ter, no m??ximo, 2 MB</i></b></h6>
<div id="anexos" class="modal-body">
Escolha um regime, um cargo e um n?�vel para anexar os documentos
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../bootstrap/_bootstrap/js/enviar_formulario_adicionar_funcionario.js"></script>
</body>
</htlm>
Here is the AJAX code, being called as enviar_formulario_adicionar_funcionario.js:
$(document).ready(function(){
$("#criar").click(function(){
event.preventDefault();
var dados = new FormData(document.getElementById("adicionar_funcionario"));
$.ajax({
url: '../utilities/criarfuncionario.php',
method: 'POST',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: {
data: dados
},
success: function(resultado){
alert(resultado.erronomecompleto);
}
})
})
})
And here is the page being sent the data (again some data was removed as it was not relevant to the problem):
<?php
if (((isset($_POST['nomecompleto'])) || (isset($_POST['nomesocial'])) ||
(isset($_POST['nomeartistico'])) || (isset($_POST['telefone'])) ||
(isset($_POST['rg'])) || (isset($_POST['cpf'])) || (isset($_POST['email'])) ||
(isset($_POST['datanasc'])) || (isset($_POST['endereco'])) ||
(isset($_POST['bairro'])) || (isset($_POST['complemento'])) ||
(isset($_POST['cidade'])) || (isset($_POST['cep'])) ||
(isset($_POST['datacontratacao'])) || (isset($_POST['cargo'])) ||
(isset($_POST['projeto'])) || (isset($_POST['datasaida'])) ||
(isset($_POST['regime'])) || (isset($_POST['telefone'])) ||
(isset($_FILES['foto'])) || (isset($_POST['uf'])) ||
(isset($_POST['numero'])) || (isset($_POST['inicio_ferias'])) ||
(isset($_POST['fim_ferias']))) &&
(strpos($_SERVER['REQUEST_URI'], 'cadastro_convite') == false)){
echo json_encode(array ('erronomecompleto' => 'Passei aqui'));
$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$query_campo_obrigatorio = "SELECT * FROM campo_obrigatorio";
$campo_obrigatorio_banco = $conn->prepare($query_campo_obrigatorio);
$campo_obrigatorio_banco->execute();
while($campo_obrigatorio = $campo_obrigatorio_banco->fetch(PDO::FETCH_ASSOC)){
if($campo_obrigatorio['campo_nomecompleto'] == '1'){
if((empty($dados['nomecompleto'])) || (str_replace(" ", "", $dados['nomecompleto']) == "")){
$erronomecompleto = 'Preencha este campo';
}
if(!preg_match("/^[a-zA-Z-' \pL]*$/u", limpapost($dados['nomecompleto']))){
$erronomecompleto = "Apenas letra e espa?�os em branco neste campo";
}else{
$nomecompleto = limpapost($dados['nomecompleto']);
}
}else{
if((empty($dados['nomecompleto'])) || (str_replace(" ", "", $dados['nomecompleto']) == "")){
$nomecompleto = "";
}
if(!preg_match("/^[a-zA-Z-' \pL]*$/u", limpapost($dados['nomecompleto']))){
$erronomecompleto = "Apenas letra e espa?�os em branco neste campo";
}else{
$nomecompleto = limpapost($dados['nomecompleto']);
}
}
When I put the echo json_encode inside the IF conditions, I don't get a response, however, if I put it outside the IF conditions, I get the return "Passei aqui".
So I came to the conclusion that my $POST['anything'] is probably not getting anything.
I also tried to pass a value to any field and send the data (to see if it entered the IF conditions), however, I didn't get a return.
I apologize in advance, as I am new to this subject.
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Bootstrap is not exclusively a CSS framework, but its most popular features are CSS-centric. These include a powerful grid, icons, buttons, map components, navigation bars, and more.
https://getbootstrap.com/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.