i have a html form with two fields that can added dynamically using javascript, but i can't validate the arrays of inputs in my request file
please see form below
{!!Form::open(['route'=>'create_course.store','class'=>'ed_contact_form ed_toppadder40', 'files'=>'true'])!!}
<div class="form-group {!!$errors->has('name')?'has-error':''!!}">
{!!Form::text('name',null,['class'=>'form-control', 'placeholder'=>'Titre du cours'])!!} {!!$errors->first('name', '<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!! $errors->has('description')?'has-error':''!!}">
{!!Form::textarea('description', null,['class'=>'form-control','placeholder'=>'Description du Cours'])!!}
{!!$errors->first('description','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('category')?'has-error':''!!}">
{!!Form::select('category' ,array(
'Choisir la Catégorie du cours',
'1'=>'Développement Web',
'2'=>'Développement mobile',
'3'=>'Business management',
'4'=>'Langues',
'5'=>'Motivation'
),['class'=>'form-control','id'=>'selectCat'])!!}
{!!$errors->first('category','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('price')?'has-error':''!!}">
{!!Form::text('price','Gratuit',['class'=>'form-control','placeholder'=>'price'])!!}
{!!$errors->first('price','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('sale')?'has-error':''!!}">
{!!Form::number('sale',null,['class'=>'form-control','placeholder'=>'Prix Promo'])!!}
{!!$errors->first('sale','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('langue')?'has-error':''!!}">
{!!Form::select('langue', array(
'Langue du cours',
'Moore'=>'Moore',
'Dioula'=>'Dioula',
'Wolof'=>'Wolof',
'Swahili'=>'Swahili',
'Fula'=>'Fula',
'Yoruba'=>'Yoruba',
'Twi'=>'twi'
),['class'=>'form-control','id'=>'selectLangue'])!!}
{!!$errors->first('langue','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('duration')?'has-error':''!!}">
{!!Form::number('duration','Gratuit',['class'=>'form-control','placeholder'=>'Durée du cours en semaines'])!!}
{!!$errors->first('duration','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('image')?'has-error':''!!}">
{!!Form::label('imageCourse','Image du Cours')!!}
{!!Form::file('image',['class'=>'form-control','placeholder'=>'image du cours','id'=>'imageCourse'])!!}
{!!$errors->first('image','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!! $errors->has('video[]')?'has-error':''!!}">
{!!Form::label('CourseVideo', 'Les Vidéos de votre Cours')!!}
<div class="lesson_container">
<div>
{!!Form::text('lesson_title[]',null,['class'=>'form-control','placeholder'=>'Titre de la Lesson'])!!}
{!! Form::file('video[]',['class'=>'form-control','id'=>'CourseVideo'])!!}
{!!
$errors->first('video[]','<small class="help-block">:message</small>')
!!}
</div>
<div class="row"></div>
<br>
{!!Form::button('Ajouter une lesson <i class="fa fa-plus" aria-hidden="true"></i>
',['class'=>'btn ed_btn ed_orange pull-left','id'=>'add_lesson'])!!}
</div>
<br>
</div>
{!!Form::hidden('prof_id',$prof_id)!!}
{!! Form::submit('Enregistrer',['class'=>'btn ed_btn ed_orange pull-right'])!!}
{!!Form::close()!!}
my script to add fiels dynamically
$(document).ready(function()
{
var wrapper=$(".lesson_container");
var add=$("#add_lesson");
$(add).click(function(e)
{
e.preventDefault();
$(wrapper).append('<br> <br><br><div><label for="newvideo">Ajouter une Video</label><input type="text" name="lesson_title[]" value="" class="form-control", placeholder="Titre de la lesson" id="newvideo"><input type="file" name="video[]" class="form-control"><div></div><br><button href="#" class="btn-primary" id="delete">Suprimer <i class="fa fa-trash-o" aria-hidden="true"></i></button></div>')
});
$(wrapper).on("click","#delete", function(e){
e.preventDefault();
$(this).parent('div').remove();
});
});
and my Request code
public function rules()
{
$rules=[
'name'=>'required|string|max:255',
'description'=>'required|string',
'category'=>'required|string',
'price'=>'required|string',
'sale'=>'string',
'langue'=>'required|string',
'duration'=>'required|integer',
'image'=>'required|image',
'prof_id'=>'required|integer'
//
];
var_dump($this->input('video'));
$videos=count($this->input('video'));
foreach(range(0,$videos) as $index)
{
$rules['video'.$index]='file|mimes:mp4,mov,wmv';
}
$lessons=count($this->input('lesson_title'));
foreach(range(0,$lessons) as $idx)
{
$rules['lesson_title.'.$idx]='required|string';
// echo $rules['lesson_title.'.$idx];
// var_dump($this->input('lesson_title'));
}
return $rules ;
}
}
When i print the two arrays $this->input('lesson_title') and $this->input('video') i get NULL means the arrays are empty .
What can be the issue here ? any help ?
Related
Im having a form with several input fields and im trying to do a js script that while i click on a button my inputs become empty and my form does not submit.
This is my form:
let btnClear = document.querySelector('button');
let inputs = document.querySelector('inputs');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = ' ');
});
let $departemento = document.getElementById('departamento')
let $provincia = document.getElementById('provincia')
let $distrito = document.getElementById('distrito')
let departamentos = ['Argentina', 'Brasil']
let provincias = ['Bs As', 'Cordoba', 'San Pablo']
let distritos = ['San Miguel', 'San Nicolas', 'Tigre', 'Belgrano', 'Calamuchita', 'La falda', 'Gral Belgrano', 'Santa Marta', 'Loa Loa']
function mostrarLugares(arreglo, lugar) {
let elementos = '<option selected disables>--Seleccione--</option>'
for(let i = 0; i < arreglo.length; i++) {
elementos += '<option value="' + arreglo[i] +'">' + arreglo[i] +'</option>'
}
lugar.innerHTML = elementos
}
mostrarLugares(departamentos, $departemento)
function recortar(array, inicio, fin, lugar) {
let recortar = array.slice(inicio, fin)
mostrarLugares(recortar, lugar)
}
$departemento.addEventListener('change', function() {
let valor = $departemento.value
switch(valor) {
case 'Argentina':
recortar(provincias, 0, 2, $provincia)
break
case 'Brasil':
recortar(provincias, 2, 3, $provincia)
break
}
$distrito.innerHTML = ''
})
$provincia.addEventListener('change', function() {
let valor = $provincia.value
if(valor == 'Bs As') {
recortar(distritos, 0, 4, $distrito)
} else if(valor == 'Cordoba') {
recortar(distritos, 4, 7, $distrito)
} else {
recortar(distritos, 7, 9, $distrito)
}
})
<div class="container">
<div class="row">
<div class="col-12">
<form method="post" action="ServletPacientes">
<h1 class="h1 mb-5" >Ingresar nuevo paciente</h1>
<div class="form-row">
<div class="form-group col-md-4">
<div>
<label>Nombre:</label>
<input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtNombre" title="Ingrese su nombre" required /> </div>
</div>
<div class="form-group col-md-4">
<div>
<label>Apellido:</label>
<input type="text" onkeypress="return checkLetras(event)" class="form-control" name="txtApellido" required="">
</div>
</div>
<div class="form-group col-md-4">
<label>DNI: </label>
<input type="text" onkeypress="return check(event)" maxlength="8" minlength="7" class="form-control" name="txtDNI" required>
</div>
<div class="form-group col-md-4">
<label>Correo electrónico: </label>
<input type="email" class="form-control" name="txtCorreo" required>
</div>
<div class="form-group col-md-4">
<label>Teléfono: </label>
<input type="text" onkeypress="return check(event)" class="form-control" name="txtTelefono" required>
</div>
<div class="form-group col-md-4">
<label>Fecha de nacimiento: </label>
<input type="date" class="form-control " name="txtFechaNac" required>
</div>
<div class="form-group col-md-4">
<label for="departamento" > Nacionalidad</label>
<select name="comboNacionalidad" id="departamento" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="form-group col-md-4">
<label for="provincia"> Provincias</label>
<select name="comboProvincia" id="provincia" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="form-group col-md-4">
<label for="distrito" > Localidades</label>
<select name="comboLocalidad" id="distrito" class="form-control ">
<!-- cargaremos las etiquetas de option con javascript -->
</select>
</div>
<div class="col-12">
<input onclick="confirmarAgregar(event)" type="submit" class="btn btn-success" value="Aceptar" name="btnAceptar">
<button type="" class="btn btn-outline-primary btnClear">Limpiar campos</button>
</div>
</div>
</form>
</div>
</div>
</div>
For some reason my form is being submitted and redirecting me to another page and my texts are never emptying. I took the submit type to my but and still does not work.
The confirmAgregar function, wherever it's defined, needs to be updated as so:
function confirmAgregar(event){
event.preventDefault()
// ... rest of your code
}
The default behavior of an HTML form submission event is to refresh the page. When you use JavaScript to handle the form submission, you usually want to prevent that behavior, then let your handle submit function perform whatever logic your form needs to do.
For preventing form submit you need to call preventDefault() on form submit event:
<form method="post" action="ServletPacientes" onsubmit="event.preventDefault()">
...
</form>
For clearing inputs you need to set correct tag name, select them all and make array to iterate them:
let inputs = [...document.querySelectorAll('input')];
Or you can just reset all your form:
const form = document.querySelector("form");
form.reset(); // reset all inputs and form elements inside this form
This question already has answers here:
why is jQuery click event firing multiple times
(5 answers)
Closed 11 months ago.
So, I have a project in laravel and now i'm working on the CRUD, specifically in the Update. Here I've a btn modal that show me the dates for edit and there I´ve a select dynamic.
The table with the btn:
#foreach ($mascotas as $mascota)
<tr>
<td class="text-center">{{$mascota->name}}</td>
<td class="text-center"> {{$mascota->especie}}</td>
<td class="text-center">{{$mascota->raza}}</td>
<td> <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#modalEditCli"
onclick="modalEdit('{{$mascota->id}}', '{{$mascota->name}}', '{{$mascota->especie}}',
'{{$mascota->razaId}}', '{{$mascota->raza}}')"> <i class="fa fa-edit"></i> </button>
</td>
</tr>
#endforeach
#include('mascotas.modal_editar')
So, in the btn I'm calling the modal and the JS function at the same time.
The modal:
<div class="modal fade" id="modalEditCli" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form action="{{route('mascotas.store')}}" method="get" class="formularin"> #csrf
<div class="row">
<div class="col-4">
<div class="mb-3">
<label for="name" class="form-label"><b>Nombre Mascota:</b> <span class="text-secondary">*</span></label>
<input class="form-control" type="text" name="mascota_nm" id="mascota_nm" value="" required>
</div>
</div>
<div class="col-4">
<div class="mb-3">
<label for="especie" class="form-label"><b>Especie:</b> <span class="text-secondary">*</span></label>
<select class="form-control especie" name="especie" id="especie" required>
<option name="especie" value="0">Otro...</option>
<option name="especie" value="1">Perro</option>
<option name="especie" value="2">Gato</option>
</select>
</div>
</div>
<div class="col-4">
<div class="mb-3">
<label for="raza" class="form-label"><b>Raza:</b> <span class="text-secondary">*</span></label>
<select class="form-control raza" name="raza" id="raza" required>
<option value="0">Otro...</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
<button type="button" class="btn btn-warning"> <i class="fa fa-edit"></i> Editar</button>
</form>
</div>
</div>
</div>
</div>
And here my JS function for the Select:
<script>
function modalEdit(id, name, especie, razaId, raza){
$('#id').val(id);
$('#mascota_nm').val(name);
$('.especie').val(especie);
$(".raza").prop('disabled', true); // Aplica el atributo "disabled" en el select.
$(".raza").html("<option value='"+ razaId +"'>"+ raza +"</option>"); // Limpia los datos del Select y solo deja la raza.
$(".especie").change(function(){
$(".raza").html("<option value='0'>Otro...</option>"); // Limpia los datos del Select y solo deja la opcion "Otro..."
var selectEspe = $('.especie').val();
$.post({
url: '/mascotas/dinamicQuery',
method: 'POST',
data: {
selectEspe,
_token: $('input[name="_token"]').val()
}
}).done(function(res){
$(".raza").prop('disabled', false); // Elimina el atributo "disabled"
var razas = JSON.parse(res); // Lee el archivo Json
$.each(razas, function(key, value){
var consulta = $(".raza").append('<option name="' + value.id + '">' + value.raza + '</option>');
});
});
});
}
</script>
And for last the Laravel query:
public function dinamicQuery(Request $request){
$especie = $request->selectEspe;
$razas = Especie::all()->where('especie', '=', $especie);
return response(json_encode($razas))->header('Content-type', 'text/plain');
}
So, the js query and the rest is working, if I open my modal it once the js query runs perfectly. But the problem is when I open any modal edit of the table for a second time o more. The "each" of my js query it runs as many times as modal is opened and I don´t know how why or how I can stop it.
Thanks for everything!
The problem is that every time when you click the edit <button/> it calls the modalEdit() function that attaches a new $(".especie").change() event.
Perhaps, the best solution is to move $(".especie").change() outside of the modalEdit() function. A quick workaround would be the .one()
Example:
<script>
function modalEdit(id, name, especie, razaId, raza){
$('#id').val(id);
$('#mascota_nm').val(name);
$('.especie').val(especie);
$(".raza").prop('disabled', true); // Aplica el atributo "disabled" en el select.
$(".raza").html("<option value='"+ razaId +"'>"+ raza +"</option>"); // Limpia los datos del Select y solo deja la raza.
}
$(".especie").change(function(){
$(".raza").html("<option value='0'>Otro...</option>"); // Limpia los datos del Select y solo deja la opcion "Otro..."
var selectEspe = $('.especie').val();
$.post({
url: '/mascotas/dinamicQuery',
method: 'POST',
data: {
selectEspe,
_token: $('input[name="_token"]').val()
}
}).done(function(res){
$(".raza").prop('disabled', false); // Elimina el atributo "disabled"
var razas = JSON.parse(res); // Lee el archivo Json
$.each(razas, function(key, value){
var consulta = $(".raza").append('<option name="' + value.id + '">' + value.raza + '</option>');
});
});
});
</script>
My question is, I'm posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I'm losing the ID somewhere, could you help me? Here is my code:
Here is my modal HTML:
<div class="modal fade" id="modalUpdatePeriodico" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered " role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Prontuário médico</h4>
<!-- para pegar o id do meu campo -->
<input type="hidden" id="hiddenIdPeriodic"/>
</div>
<div class="modal-body">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- Inicio do Formulario de Pesquisa -->
<form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">
<!-- Form Data e Qtde dias -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="dateExam">Data da Realização</label>
<input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">
</div>
<div class="form-group col-md-6">
<label for="statusExam">Status</label>
<select class="form-control select2" id="statusExam" name="statusExam">
<option value="1">Inapto</option>
<option value="2">Apto</option>
</select>
</div>
</div>
</form>
<!-- Fim do Formulario de Pesquisa -->
</div>
<!--/.col (right) -->
</div>
<!-- /.row -->
</div>
<div class="modal-footer">
<button
type="button"
id="btnSavePeriodic"
class="btn btn-success"
data-dismiss="modal"
onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
Salvar
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
Here is my DataTable JS code:
function tbPeriodic() {
// Definição do id da tabela como um dataTable
$("#tbPeriodico").DataTable({
"ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
sorting: false,
"columns":
[
{ "data": "id" ,
render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
data = '' + row.id + '';
return data;
}
},
{ "data": "ult_exame" },
{ "data": "tipo_exame" },
{ "data": "status_exame" },
{ "data": "prox_exame" }
]
});
}
Here is my function to post my id into a input hidden:
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
Here is my datepicker function:
$('.datepicker-calendar').datepicker({
autoclose: true
});
So, when I input a date from my datepicker the console shows me undefined, could you help me?
Thanks a lot!
I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.
#1
The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable <a> like below and get rid of the modal call.
dataTable
data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
Then get rid of
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
and change it to
$(document).on('click', '.clickme', function() {
var id = $(this).data('id');
$('#modalUpdatePeriodico').modal('show');
$('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
console.log(id);
})
#2
The date thing is a different event so add this to get the date
$('.datepicker-calendar').datepicker({
autoclose: true,
onSelect: function(date) {
console.log(date)
}
})
I come to ask for help because I have a problem that persists for three days and I can't understand where the problem is. I have a form on an HTML page here :
<form id="contactformpage">
<div class="messages"></div>
<div class="form-group row">
<label for="societepage" class="col-sm-6 col-form-label">Société</label>
<div class="col-sm-6 champ">
<input type="text" name="societe" class="form-control" id="societepage" placeholder="Nom de la société" aria-describedby="indicsocietepage">
<small id="indicsociete" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="adressepage" class="col-sm-6 col-form-label" >Adresse</label>
<div class="col-sm-6 champ">
<input type="text" name="adresse" class="form-control" id="adressepage" placeholder="Adresse">
</div>
</div>
<div class="form-group row">
<label for="codepostaletvillepage" class="col-sm-6 col-form-label" >Code postal & ville</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="codepostaletville" id="codepostaletvillepage" placeholder="Code postal & ville">
</div>
</div>
<div class="form-group row">
<label for="contactpage" class="col-sm-6 col-form-label">Nom du contact</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="contact" id="contactpage" placeholder="Nom du contact">
</div>
</div>
<div class="form-group row">
<label for="telephonepage" class="col-sm-6 col-form-label">Téléphone</label>
<div class="col-sm-6 champ">
<input type="text" class="form-control" name="téléphone" id="telephonepage" placeholder="Numéro de téléphone" aria-describedby="indictelephonepage">
<small id="indictelephonepage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label for="mailpage" class="col-sm-6 col-form-label">Adresse mail</label>
<div class="col-sm-6 champ">
<input type="email" class="form-control" name="mail" id="mailpage" placeholder="Entrez votre adresse mail" aria-describedby="indicmailpage">
<small id="indicmailpage" class="form-text text-muted"> * Obligatoire </small>
</div>
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="selecmarque" aria-describedby="indicmarquepage"> Marque du véhicule </label>
<div class="col-sm-6 champ">
<select class="form-control" name="marque" style="height:20px;padding-bottom:0;padding-top:1;" onchange="generechoixmodele('selecmarque','apreschoixmarquepage','apreschoixmodelepage','nommodelepage','choixmodelepage','choixtypepage');" id="selecmarque">
<option selected> Séléctionnez </option>
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmarquepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix de la marque -->
<label class="col-sm-6 col-form-label" for="apreschoixmarquepage" aria-describedby="indicmarque" id="nommodelepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="modele" style="height:20px;padding-bottom:0;padding-top:1;" id="choixmodelepage" onchange="generechoixtype('selecmarque','choixmodelepage','apreschoixmodelepage','nomtypepage','choixtypepage');">
</select>
</div>
</div>
<div class="form-group row" id="apreschoixmodelepage" style="display:none;"> <!-- Liste déroulante qui apparait après le choix du modèle -->
<label class="col-sm-6 col-form-label" for="apreschoixmodelepage" aria-describedby="indicmarque" id="nomtypepage"></label>
<div class="col-sm-6 champ">
<select class="form-control" name="type" style="height:20px;padding-bottom:0;padding-top:1;" id="choixtypepage">
</select>
</div>
</div>
<p> Je souhaite recevoir les catalogues suivants (dynamique)</p>
<div id="choixcataloguepage">
</div>
<div class="form-group row">
<label class="col-sm-6 col-form-label" for="commentairepage">Commentaire</label>
<div class="col-sm-6 champ">
<textarea class="form-control" name="commentaire" id="commentairepage" rows="1"></textarea>
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-6 col-form-label">Captcha</label>
<div class="col-sm-6 champ">
<h6> Captcha à rajouter après </h6>
</div>
</div>
<input type="submit" class="btn" id="submitpage">
</form>
And when I click on the button of this form, I send the data entered by the user thanks to an Ajax request on a php page:
$(document).ready(function(){
$("#submitpage").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'sendform.php',
dataType: "JSON",
data: {
societe : $("#societepage").val(),
adresse : $("#adressepage").val(),
codepostaletville : $("#codepostaletvillepage").val(),
contact : $("#contactpage").val(),
telephone : $("#telephonepage").val(),
mail : $("#mailpage").val(),
marqueclient : $("#selecmarque").val(),
modeleclient : $("#choixmodelepage").val(),
typeclient : $("#choixtypepage").val(),
commentaire : $("#commentairepage").val()
},
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contactformpage').find('.messages').html(alertBox);
// empty the form
$('#contactformpage')[0].reset();
}
}
})
});
});
I know it's possible to do $(this).serialize() for forms directly but I'd like to do that already. Here is the PHP script in question, so I send my data with the POST method, the problem is that this script tells me all the time "Form is empty" which means that the data was not sent with POST (since $ _POST is empty). And when I try to make an echo ($_SERVER['HTTP_X_REQUESTED_WITH']), the php script returns an empty string, which means that the Ajax request was not made.
<?php
/*
THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
AND ALSO SMTP TO SEND THE EMAILS
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer/PHPMailer-master/src/Exception.php';
require 'PHPMailer/PHPMailer-master/src/SMTP.php';
require 'PHPMailer/PHPMailer-master/src/OAuth.php';
require 'PHPMailer/PHPMailer-master/src/POP3.php';
/*
* CONFIGURE EVERYTHING HERE
*/
// an email address that will be in the From field of the email.
$fromEmail = 'lyes.tifoun#hotmail.fr';
$fromName = 'Demo contact form';
// an email address that will receive the email with the output of the form
$sendToEmail = 'lyestfn#gmail.com';
$sendToName = 'Lyes Tifoun';
// subject of the email
$subject = 'New message from contact form';
// smtp credentials and server
$smtpHost = 'smtp.gmail.com';
$smtpUsername = 'nom_utilisateur';
$smtpPassword = 'mdp';
$fields = array('societe' => 'Société', 'adresse' => 'Adresse', 'codepostaletville' => 'Code postal et ville', 'contact' => 'Nom du contact', 'téléphone' => 'Numéro de téléphone', 'mail' => 'Adresse mail', 'marque' => 'Marque du véhicule', 'modele' => 'Modèle du véhicule', 'type' => 'Type du véhicule', 'commentaire' => 'Commentaire');
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
error_reporting(E_ALL & ~E_NOTICE);
try {
if (count($_POST) == 0) {
throw new \Exception('Form is empty');
}
$emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
$emailTextHtml .= "<table>";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
}
}
$emailTextHtml .= "</table><hr>";
$emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = gethostbyname($smtpHost);
$mail->Port = 587;
$mail->isHTML(true);
$mail->SMTPOptions = array('ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true));
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
$mail->addReplyTo($from);
$mail->Subject = $subject;
$mail->Body = 'test';//$emailTextHtml;
$mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
$mail->Debugoutput = 'html';
if (!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (\Exception $e) {
// $responseArray = array('type' => 'danger', 'message' => $errorMessage);
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
I would like to understand why my request doesn't work because I don't think I made any syntax or other errors.
Here is the script used for the JQuery library in my HTML file.
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
And I use WAMPServer to run my site locally, I already did my research but could the problem come from there by chance?
Thank you in advance
I come back to you to inform you that my data is finally sent with $_POST as shown by the network panel:
enter image description here
I've also made a var_dump($_SERVER) and the $_SERVER['HTTP_X_REQUESTED_WITH'] value is "XML HTTPREQUEST" which indicates that the Ajax request has been launched. Now I have an other problem : I don't have a client-side response: currently the program seems to validate the condition if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') and I have an echo($encoded) in JSON format as shown below :
enter image description here
Therefore I should have a client-side response, which is not the case actually.
Thanks a lot for your responses and sorry for my bad english.
I am trying to get a property from a select tag and use in a property object.
Here is my html:
<div id="app">
<h3>{{title}}</h3>
<div class="form">
<div class="form-group">
<div class="form-group">
<label>Note Title</label>
<input class="form-control" type="text" v-model="note.title">
</div>
<div class="form-group">
<label>Note text</label>
<textarea class="form-control" v-model="note.text"></textarea>
</div>
<div class="form-group">
<label>Cor</label>
<select v-model="note.cor">
<option disabled value="">Selecione a cor</option>
<option value="blue">Azul</option>
<option value="green">Verde</option>
</select>
<span>Cor Selecionada: {{ note.cor }}</span>
</div>
<button class="btn btn-primary" #click="addNote">Submit</button>
</div>
<div class="col-sm-12">
<div class="col-sm-4" v-for="(note, index) in notes">
<button class="close" #click="removeNote(index)">×</button>
<div class="card-block">
<h4 class="card-title" v-bind:style="{ color: note.cor }">{{note.title}}</h4>
<h6 class="card-subtitle mb-2 text-muted">{{note.date}}</h6>
<p class="card-text">{{note.text}}</p>
</div>
</div>
</div>
</div>
</div>
Here is the Js:
var app = new Vue({
el: '#app',
data: {
title: 'Notemaster',
note: {
title: '',
text: '',
cor: ''
},
notes: [
{
title: 'Visit Hawaii',
text: 'just kiddind lol',
date: new Date(Date.now()).toLocaleString(),
cor:'blue'
}
]
},
methods: {
addNote() {
let { text, title } = this.note
this.notes.push({
text,
title,
date: new Date(Date.now()).toLocaleString(),
cor
})
},
removeNote(index) {
<!-- apaga o número de itens dispostos no segundo parametro-->
this.notes.splice(index, 1)
}
}
});
The value of the select tag works to show at <span>Cor Selecionada: {{ note.cor }}</span>;
It works to show the color of the title at <h4 class="card-title" v-bind:style="{ color: note.cor }">{{note.title}}</h4>
But I can't create a new note.
The error shown is that cor in this.notes.push({ ... cor }) is not defined.
Thanks in advance
The error message is pretty self-explanatory, cor is not defined in that scope.
Perhaps you meant to do this:
let { text, title, cor } = this.note
^^^