i need to put javascript validation in django - javascript

I have a javascript validation but it doesn't work for me, I think it may be sweet alert
I think that sweetalert is validating before the validation that I have in javascript
javascript validation:
const $email_validation = document.getElementById('email_validation');
const $contrasena_validation = document.getElementById('contrasena_validation');
const $formularioempleado = document.getElementById('formularioempleado');
var $expresion_email, $expresion_password;
$expresion_email = /^([\da-z_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
$expresion_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
(function() {
$formularioempleado.addEventListener('submit', function(e) {
let email=String($email_validation.value).trim();
let contrasena=String($contrasena_validation.value).trim();
if(email.length === 0 || contrasena.length === 0){
alert("Todos los campos son obligatorios");
e.preventDefault();
}
else if(email.length>100){
alert("El correo es muy largo");
e.preventDefault();
}
else if(!$expresion_email.test(email)){
alert("El correo no es valido");
e.preventDefault();
}
else if(contrasena.length>255){
alert("La Contraseña es muy larga");
e.preventDefault();
}
else if(!$expresion_password.test(contrasena)){
alert("Contraseña: Debe contener al menos un numero y una letra mayúscula y minúscula, y al menos 8 caracteres o más");
e.preventDefault();
}
e.preventDefault();
});
})();
createuser.html:
{% extends 'app/base.html' %}
{% block contenido %}
{% load crispy_forms_tags%}
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-12 col-md-6 content m-0 mt-2 mb-2 pt-2 pb-2" >
<form class="p-0" method="POST" id="formularioempleado">
{% csrf_token %}
<h2 class="text-center">Crear Empleado</h2>
<hr>
{{empleado | crispy}}
<input class="btn btn-primary mb-2" type="submit" value="Crear Usuario">
<hr>
</form>
</div>
<div class=" col-md-3">
</div>
</div>
</div>
views.py(here i have the message of the sweetalert)
def crearusuario(request):
data = {
'empleado': CrearEmpleadoForm()
}
if request.method=="POST":
if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'):
usersave= Empleado()
usersave.rut=request.POST.get('rut')
usersave.nombres=request.POST.get('nombres')
usersave.apellidos=request.POST.get('apellidos')
usersave.correo_electronico=request.POST.get('correo_electronico')
usersave.usuario=request.POST.get('usuario')
usersave.contrasena=request.POST.get('contrasena')
usersave.activo=request.POST.get('activo')
usersave.cargo_empleado=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado')))
usersave.id_empresa=Empresa.objects.get(pk=(request.POST.get('id_empresa')))
usersave.id_unida=UnidadInterna.objects.get(pk=(request.POST.get('id_unida')))
cursor=connection.cursor()
cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+str(usersave.cargo_empleado.id)+"', '"+str(usersave.id_empresa.id)+"', '"+str(usersave.id_unida.id)+"')")
messages.success(request, "El empleado "+usersave.nombres+" se guardo correctamente ")
return render(request, 'app/crearusuario.html', data)
else:
return render(request, 'app/crearusuario.html', data)
base.html(messages of sweetalert)
{% if messages%}
{% for displaydata in messages%}
<script>
Swal.fire({
"title": "Felicitaciones",
"text": "{{displaydata}}",
"icon": "success"
})
</script>
{% endfor%}
{% endif%}
help me please!!

Related

Test if a function with multiple if/else blocks return true or false in javascript

I'm not sure if this question has been asked before or not,
I'm trying to make a validation form using Javascript.
My question is: is there any way to test if my functions validateEmailLogin() and validatePsswordLogin() returns true or false in all if/else blocks, so I can test in the function isValide() whether the two functions return true or false and do a treatment.
Ps: it's a bit messy code and any suggestions to reduce it and make it cleaner are welcome.
Here's my html and js code :
function validateEmailLogin() {
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
} else {
emailMessagePatern.classList.add("d-none");
}
}
function validatePsswordLogin() {
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
}
function isValide() {
if (validateEmailLogin() && validatePsswordLogin()) {
window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
return false;
} else {
alert('check your credentials');
}
}
My HTML
form name="loginForm" method="POST">
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small></p>
</div>
<button onclick="return isValide()" type="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
</form>
I like your code!
The message holders = nice!
I've made some modifications:
added valid flag initialized as true, set to false when not valid, and returned from both validate functions
changed isValide to valide and removed the return
removed the <form>
removed type=submit from button
button just calls valide - whatever is needed to be done - from there
commented out change of href for demonstration - uncomment when ready, actually, use location.replace(URL); instead of window.location.href = URL;
Notes:
your URL is a local file...
the email validator function is not complete (x#.com#.com - passes, for example...)
function validateEmailLogin() {
var valid=true;
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
valid=false;
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
valid=false;
} else {
emailMessagePatern.classList.add("d-none");
}
return valid;
}
function validatePsswordLogin() {
var valid=true;
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
valid=false;
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
return valid;
}
function valide() {
if (validateEmailLogin() && validatePsswordLogin()) {
alert("valid");
// window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
} else {
alert('check your credentials');
}
}
.d-none {
display:none;
}
<!-- form name="loginForm" method="POST" -->
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small>
</p>
</div>
<button onclick="valide()" xtype="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
<!-- /form -->

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

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

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 ?

Form Validation with JavaScript and PHP (Not refresh page on submit)

I am trying to do a form validation with JS that shows feedback as the user types. But of course when submitted the form it's sent using PHP. I already managed to do all of this the only problem I am having now is that when the form is submitted the page refreshes and my "Successfully sent" message cannot be seen. Here is my code and thanks a lot! :D
HTML FORM
<form method="post" id="emailForm" action="?">
<div class="form-group">
<label for="email">Email</label>
<input type="email" placeholder="ejemplo#gmail.com" class="form-control" name="email" id="email"/>
<p class="alert alert-danger errorEmail"></p>
</div>
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" placeholder="María Rodriguez" class="form-control" name="name" id="name"/>
<p class="alert alert-danger errorName"></p>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" placeholder="Garantía producto" class="form-control" name="asunto" id="asunto" /><span class="badge badgeA"></span>
<p class="alert alert-danger errorAsunto"></p>
</div>
<div class="form-group">
<label for="mensaje">Mensaje</label>
<textarea placeholder="Ingrese su mensaje aquí, trate de ser lo más claro y conciso posible." name="mensaje" id="mensaje" class="form-control" rows="7"></textarea><span class="badge badgeM"></span>
<p class="alert alert-danger errorMensaje"></p>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Enviar!"/>
Field to display feedback of submission
<div class="alert alert-success enviado">
</div>
<div class="alert alert-danger noEnviado">
</div>
JavaScript (jQuery)
$(function() {
$(".errorEmail").hide();
$(".errorName").hide();
$(".errorAsunto").hide();
$(".errorMensaje").hide();
$(".enviado").hide();
$(".noEnviado").hide();
var error = false;
$('#email').keyup(function(){
checkEmail();
});
$('#name').keyup(function(){
checkName();
});
$('#asunto').keyup(function(){
checkAsunto();
});
$('#mensaje').keyup(function(){
checkMensaje();
});
function checkEmail() {
var email = $('#email').val();
error = false;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email)) {
$('.errorEmail').hide();
}
else {
$('.errorEmail').html("Ingrese un correo electrónico válido.")
$('.errorEmail').show();
error = true;
}
}
function checkName() {
var name = $('#name').val().length;
var minName = 5;
var cantidad = - (name - minName);
error = false;
if (name < 5){
$('.errorName').html("Por favor ingrese su nombre. <b>Mínimo " + cantidad + " caracteres.</b>");
$('.errorName').show();
error = true;
}
else {
$('.errorName').hide();
}
}
function checkAsunto() {
var asunto = $('#asunto').val().length;
var minAsunto = 10;
var cantidad = - (asunto - minAsunto);
error = false;
if (asunto <10){
$('.errorAsunto').html("Por favor ingrese un asunto.<b> Mínimo " + cantidad + " caracteres.</b>");
$('.errorAsunto').show();
error = true;
}
else {
$('.errorAsunto').hide();
}
}
function checkMensaje() {
var email = $('#mensaje').val().length;
var minMensaje = 20;
var cantidad = - (email - minMensaje);
error = false;
if (email < 20){
$('.errorMensaje').html("Por favor ingrese un mensaje. <b> Mínimo " + cantidad + " caracteres. </b>");
$('.errorMensaje').show();
error = true;
}
else {
$('.errorMensaje').hide();
}
}
$('#emailForm').submit( function() {
checkEmail();
checkName();
checkAsunto();
checkMensaje();
if(error === false) {
$('.enviado').html("Mensaje enviado exitosamente");
$('.enviado').fadeIn(500);
$('.noEnviado').fadeOut(500);
return true;
} else {
$('.noEnviado').html("Ups... hubo un problema");
$('.noEnviado').fadeIn(500);
$('.enviado').fadeOut(500);
return false;
}
});
});
PHP
The PHP code is really simple some how it doesn't let me display it here but it just get's the $_POST values on the form and sends them using email();
Thanks guys
Instead of returning true replace it with an Ajax post request to the same script, on success show the message you wish.

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