Tengo un formulario que puede agregar datos a una base de datos. Todo está hecho con jquery y ajax, así que cuando presiona enviar, valida el código y luego, si todo está correcto, envía los datos de la publicación sin actualizar la página. El problema es que el formulario funciona la primera vez, pero luego cuando vas a enviar otra entrada con el formulario, no funciona. Pensé que tenía algo que ver con laFormulario de Jquery que solo funciona la primera vez que lo envía, y no el segundo
$(document).ready(function(){
Pero realmente no tienen idea. He pegado parte del código a continuación. Es bastante largo, pero esto debería proporcionar información suficiente para saber lo que está haciendo. El archivo js todo está en http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div(that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
En este momento, la primera vez que se utiliza la forma que funciona muy bien. y el botón vuelve a habilitarse, pero luego, cuando intenta hacer otra entrada y hace clic en el botón, no ocurre nada.
¡Gracias por la ayuda!
EDIT: Después de que el formulario envía la primera vez que el botón está habilitado todavía y puede hacer clic en él, pero cuando se hace clic en él no pasa nada ... incluso si no rellena el formulario. Es como si el evento click del formulario no se activara la primera vez.
EDIT2 Según lo solicitado, voy a publicar el código HTML, está detrás de un sitio protegido con contraseña, por lo que no puedo enviarle el enlace de la página.
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
Edit3 Hay otra Ajax en la página también, pero está escrito en javascript recta. No estoy seguro de si eso afectaría la funcionalidad de alguna manera. Pero si es necesario, puedo publicar ese ajax también.
EDIT4 que tiene el tutorial original del http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ y modificaron
EDITAR Después de poner en algunas alertas diferentes, descubrí que no hace la declaración condicional if(error==false)...
idea de por qué?
De vistazo rápido, esto debería funcionar bien. Agregue alertas en líneas clave y vea dónde se detiene o, mejor aún, elimínelas con Firebug o algo equivalente, y avísenos los resultados. –
Sí, en particular, usaría una "alerta()" o "console.log()" para asegurarme de que el manejador "click" se invocó en la segunda pasada. – Pointy
El evento click no se está llamando la segunda vez. Puede hacer clic en el botón todo lo que quiera, pero no sirve de nada – Bill