How to get a ID in a modal coming by dataTable? - javascript

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)
}
})

Related

My ajax query is repeated how many times I open my modal (Select Dynamic) [duplicate]

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>

AJAX values undefined with Symfony

I actually try to make an custom authentication using AJAX and Symfony but I have a problem that I can't even identify.
It seems that the AJAX part doesn't find the route because my browser console can't "recognize" my route script. I tried to identify AJAX data compared to input fields data and the problem is that AJAX returns undefined values. I'll put the different parts of my code below :
Twig modal with AJAX script :
<div class="modal fade" tabindex="-1" role="dialog" id="loginModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Connexion</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body" align="center">
<form action="#" method="POST">
<label for="pseudoMail">Pseudo ou e-mail : </label>
<input type="text" id="pseudoMail" placeholder="Pseudo ou e-mail" name="pseudoMail" required><br>
<label for="mdp">Mot de passe : </label>
<input type="password" id="mdp" placeholder="Mot de passe" name="mdp" required><br>
<input type="submit" class="btn btn-primary" id="login" value="Se connecter" />
</form>
</div>
</div>
</div>
</div>
<script src="{{ asset('js/jquery-3.5.1.min.js') }}"></script>
<script>
$(document).ready(function () {
$("#login").click(function()
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '{{ path('checkLogin') }}',
data: {
pseudo: $("input#pseudoMail").val(),//TODO Remplir l'Ajax de façon à ce que les données soient reconnues
motdepasse: $("input#mdp").val()
},
dataType: 'json',
success: function(data)
{
if(data.pseudo !== "" && data.motdepasse !== "")//TODO Modifier la condition et jouer les sons correspondants (dossier sfx)
{
setTimeout(alert("Vous êtes connecté !"), 5000);
var sound = document.createElement('audio');
sound.setAttribute('src', 'https://themushroomkingdom.net/sounds/wav/smb/smb_1-up.wav');
sound.play();
}
else
{
alert("Les identifiants ne correspondent pas. Veuillez réessayer.");
var sound = document.createElement('audio');
sound.setAttribute('src', 'https://themushroomkingdom.net/sounds/wav/smb/smb_fireworks.wav');
sound.play();
}
},
error: function(data)
{
console.log("Pseudo : " + data.pseudo);
console.log("Mot de passe : " + data.motdepasse);
console.log("Pseudo sans data : " + $('input#pseudoMail').val());
console.log("Mot de passe sans data : " + $('input#mdp').val());
console.log(data);
alert("Erreur détectée ! " + data);
}
});
});
});
</script>
The PHP script :
/**
* #Route("/checkLogin", name="checkLogin")
*/
public function checkLogin(Request $request, SessionInterface $session)//TODO vérifier les connexions pour mesures de sécurité ?
{
$pseudoMail = $request->request->get('pseudoMail');
$motdepasse = $request->request->get('mdp');
$repo = $this->getDoctrine()->getRepository(Utilisateur::class);
$pseudoDB = $repo->findOneBy(["pseudo" => $pseudoMail]);
$mailDB = $repo->findOneBy(["email" => $pseudoMail]);
$motdepasseDB = $repo->findOneBy(["motDePasse" => $motdepasse]);
if (($pseudoDB && $motdepasseDB) || ($mailDB && $motdepasseDB))
{
$session->set('login', true);
/*return $this->render('boutique/index.html.twig', [
'controller_name' => 'BoutiqueController',
]);*/
var_dump($pseudoMail . "-" . $motdepasse);
return new JsonResponse(array('pseudo' => $pseudoMail, 'motDePasse' => $motdepasse));
}
else
{
$session->set('login', false);
//$this->addFlash('flash', "Login incorrect. Veuillez réessayer.");
/*return $this->render('accueil/index.html.twig', [
'controller_name' => 'AccueilController',
]);*/
return new Response("Problème !");
}
}
As charlietfl said, you get different keys between your AJAX code and your PHP code. They should equal.
data: {
pseudo: $("input#pseudoMail").val(),
motdepasse: $("input#mdp").val()
},
In your AJAX request, keys are pseudo and motdepasse. So, in your PHP code, you should use those keys like that:
$pseudoMail = $request->request->get('pseudo');
$motdepasse = $request->request->get('motdepasse');

Validate modal-form with jquery

i have a problem with validate modal-form with jquery. If i click the button nothing happens. Instead if i write inside an input form and i click on the button it convalidate.It's like the code didn't see the javascript. I have locked the solutions of my problem many times but i can't find them. I have a separate file javascript and i put it in the head of the page where is the modal. I put also the links for the jquery library from google.
I noticed that when i open the page for the first time and press the button to validate it validate without check the parameters that i write in the script and the other times when i click the button nothing happens.
Here the links of the libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
This is my modal contain the form:
<!-- Modale -->
<div class="modal fade" id="modaleReg" tabindex="-1" role="dialog" aria-labelledby="modale" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-sm" id="modifyMod" role="document">
<!-- Contenitore modale -->
<div class="modal-content">
<!-- Header modale -->
<div class="modal-header">
<h5 class="modal-title" id="titMod">modale</h5>
<span class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">×</span>
</div>
<!-- Body modale -->
<div class="modal-body">
<!--Form per iscrizione -->
<form action="#" id="form">
<div class="form-group">
<label for="name">Nome</label>
<input id="name" name="name" type="text" class="form-control" placeholder="Nome">
</div>
<div class="form-group">
<label for="surname">Cognome</label>
<input id="surname" name="surname" type="text" class="form-control" placeholder="Cognome">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input id="email" name="email" type="email" class="form-control" aria-describedby="emailHelp" placeholder="Email">
<small id="emailHelp" class="form-text text-muted">Non condivideremo mai la tua email con nessuno.</small>
</div>
<div class="form-group">
<label for="password">Crea password</label>
<input id="password" name="password" type="password" class="form-control">
</div>
<div class="form-group">
<label for="confermaPsw">Conferma password</label>
<input id="confermaPsw" name="confermaPsw" type="password" class="form-control">
</div>
<button type="submit" class="btn btn-primary btnmod">Continua</button>
</form>
</div>
<!-- Footer modale -->
<div class="modal-footer">
</div>
<!--Fine contenitore modale -->
</div>
</div>
</div><!-- Fine modale -->
This is my javascript code:
$(document).ready(function() {
// Selezione form e definizione dei metodi di validazione
$("#form").validate({
// Definiamo le nostre regole di validazione
rules : {
// name - nome del campo di input da validare
name : {
// Definiamo il campo name come obbligatorio
required : true
},
password : {
required : true,
// Settiamo la lunghezza minima e massima per il campo password
minlength : 5,
maxlength : 8
},
email : {
required : true,
// Definiamo il campo email come un campo di tipo email
email : true
}
},
// Personalizzimao i mesasggi di errore
messages: {
name: "Inserisci il nome",
password: {
required: "Inserisci una password password",
minlength: "La password deve essere lunga minimo 5 caratteri",
maxlength: "La password deve essere lunga al massimo 8 caratteri"
},
email: "Inserisci la tua email"
},
});
});
Can you please add below code with validate function and try again
$(document).ready(function() {
// Selezione form e definizione dei metodi di validazione
$("#form").validate({
// Definiamo le nostre regole di validazione
rules : {
// name - nome del campo di input da validare
name : {
// Definiamo il campo name come obbligatorio
required : true
},
password : {
required : true,
// Settiamo la lunghezza minima e massima per il campo password
minlength : 5,
maxlength : 8
},
email : {
required : true,
// Definiamo il campo email come un campo di tipo email
email : true
}
},
// Personalizzimao i mesasggi di errore
messages: {
name: "Inserisci il nome",
password: {
required: "Inserisci una password password",
minlength: "La password deve essere lunga minimo 5 caratteri",
maxlength: "La password deve essere lunga al massimo 8 caratteri"
},
email: "Inserisci la tua email"
},
submitHandler: function(form) {
// code to submit the form
}
});
});
You can also try to add you code in modal box and it will works fine

How do i validate a dynamic input field , laravel 5.4?

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 ?

message via ajax is hiding fields

I have a problem I could not solve
I'm trying to send the message via ajax and update a div when sending the message
the only problem is that when I comment on something that updates a div field textarea and buttons just disappear
I also put a button to display the message field and buttons
Here is the code I'm using
<script type="text/javascript">
function hide_menu(){
if(document.getElementById('responder').style.display == "none"){
document.getElementById('responder').style.display = "block";
document.getElementById('button').style.display = "block"
$('html, body').animate({scrollTop:$('#responder').position().top});
}else{
document.getElementById('responder').style.display = "none"
document.getElementById('button').style.display = "none"
$('html, body').animate({scrollTop:$('#da-content-wrap').position().top});
}
}
</script>
<script type="text/javascript" language="javascript">
$(function($) {
// Quando o formulário for enviado, essa função é chamada
$("#da-ex-validate1").submit(function() {
// Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
var mensagem = $("#cleditor").val();
var user = $("#user").val();
// Fazemos a requisão ajax com o arquivo envia.php e enviamos os valores de cada campo através do método POST
$.post('<?= URL::getBase();?>form/insert/comment.php?id=<?=$_id;?>', {user: user, mensagem: mensagem }, function(resposta) {
// Quando terminada a requisição
// Exibe a div status
$("#status").slideDown();
// Se a resposta é um erro
if (resposta != false) {
// Exibe o erro na div
alert('Ocoreu um erro !');
}
// Se resposta for false, ou seja, não ocorreu nenhum erro
else {
$("#mensagens").load('<?= URL::getBase();?>load.php?id=<?= $_id;?>');
// Limpando todos os campos
$("#cleditor").val('');
}
});
});
});
</script>
Here is the HTML
<!-- Content Area -->
<div class="da-panel-content"> <img src="buildings.png" alt="" />Reply
<div id="mensagens">
<?= comments::_build($_id);?>
</div>
<form id="da-ex-validate1" class="da-form" method="post" action="javascript:func()" >
<div id="responder" style="display:none;">
<textarea id="cleditor" name="mensagem" class="large required"></textarea>
<input type="hidden" name="user" id="user" value="<? GetInfo::_id(NULL);?>"/>
</div>
<div class="da-button-row" id="button" style="display:none;">
<input type="reset" value="<?= $_LANG[137];?>" class="da-button gray left" />
<input type="submit" id="da-ex-growl-2" value="<?= $_LANG[219];?>" class="da-button red" />
</div>
</form>
</div>
where is "<?= comments::_build($_id);?>" is the list of records.
I also made ​​a page load.php practically calls the same function.
http://i.stack.imgur.com/V46Nr.jpg
sorry any mistake english :-)

Categories

Resources