Foros del Web » Programando para Internet » Javascript » Frameworks JS »

Formulario Ajax+PHP con validación usuario existe y más

Estas en el tema de Formulario Ajax+PHP con validación usuario existe y más en el foro de Frameworks JS en Foros del Web. Saludos, si no os importa os comento mi problema. Cabe decir que es lo primero que hago con ajax pero lo necesito solucionar como el ...
  #1 (permalink)  
Antiguo 29/04/2011, 19:25
 
Fecha de Ingreso: abril-2011
Mensajes: 2
Antigüedad: 13 años
Puntos: 0
Pregunta Formulario Ajax+PHP con validación usuario existe y más

Saludos, si no os importa os comento mi problema. Cabe decir que es lo primero que hago con ajax pero lo necesito solucionar como el respirar ya que ahora en mi web se dan de alta usuarios mediante el formulario y no es hasta que hacen submit que este les indica que el usuario ya existe. Así pues he intentado modificar mi formulario para que los campos se validen por ajax y compruebe si el Usuario y el E-mail son únicos.
El problema llega cuando quiero habilitar y desabilitar el botón de Submit. No se habilita y deshabilita siempre correctamente, tiene algun bug en según qué combinaciones. Os pongo el código y si alguien me recomienda algo mejor y más sencillo tipo jQuery pues mucho mejor.

Código:
// A function to handle the response from the PHP script
function handleHttpResponse() {
//function loadpage(http, vLoadarea) {


	if(http.readyState == 4) {

		// Refering to the PHP script, for every validation we'll get
		// either true or false and apply some visual changes in order to
		// get the user focusing on each field whether it's ok or not
		// If one of the input fields contains an error, the submit button
		// will be disabled, until the error (that means all errors) are
		// solved
		
		if(http.responseText == "userAvailable") {
			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
			
			document.getElementById(vLoadarea).innerHTML = http.responseText;

			document[vId].src = "img/true.png";
			sInput.style.border = "1px solid green";
			sInput.style.background = "#ffffff";
			
			return checkSubmit();
			
			
		} else if(http.responseText == "userNotAvailable") {
			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
			document.getElementById(vLoadarea).innerHTML = http.responseText;
			
			document[vId].src = "img/false.png";
			sInput.style.border = "1px solid orange";
			sInput.style.background = "#ffffff";
			
			vButton.disabled = true;
			vError.push(vId);
		}
		
		
		
		if(http.responseText == "existsEmail") {
			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
			
			document.getElementById(vLoadarea).innerHTML = http.responseText;

			document[vId].src = "img/false.png";
			sInput.style.border = "1px solid #d12f19";
			sInput.style.background = "#f7cbc2";
			
			vButton.disabled = true;
			vError.push(vId);
			
		}
		
		
		
		if(http.responseText == "false") {

			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
			var errMsg = document.getElementById(vLoadarea);
			
			document[vId].src = "img/false.png";
			sInput.style.border = "1px solid #d12f19";
			sInput.style.background = "#f7cbc2";
			
			errMsg.innerHTML = "Valor necesario o incorrecto.";

			vButton.disabled = true;
			vError.push(vId);

		}

		if(http.responseText == "true") {

			var sInput = document.getElementById(vId);
			var errMsg = document.getElementById(vLoadarea);
			
			document[vId].src = "img/true.png";
			sInput.style.border = "1px solid #338800";
			sInput.style.background = "#c7f7be";

			errMsg.innerHTML = "ok";
			
			return checkSubmit();
			
		}

		if(http.responseText == "none") {

			var sInput = document.getElementById(vId);
			var vButton = document.getElementById("submit");
			var errMsg = document.getElementById(vLoadarea);
			
			document[vId].src = "img/blank.gif";
			sInput.style.border = "1px solid #aaa";
			sInput.style.background = "#ffffff";
					
			return checkSubmit();
			
		}
		
	}

}


//AQUI SE DEBERÍA DE VERIFICAR SI TODOS LOS CAMPOS SON CORRECTOS O SI TIENEN ALGUN ERROR

function checkSubmit(){
	// We do a check if our element is in the error array, and if
	// so, we can delete it from the array
	if(vError.indexOf(vId) != -1) {
		var aId = vError.indexOf(vId);
		
		document.getElementById("errs").innerHTML = aId;
		
		vError.splice(aId, 1);
		if(vError.length > 0) {
			var vButton = document.getElementById("submit");
			
			
			vButton.disabled = true;
		} else {
			var vButton = document.getElementById("submit");
			vButton.disabled = false;
		}
	}
}
Un saludo,
  #2 (permalink)  
Antiguo 29/04/2011, 22:13
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: Formulario Ajax+PHP con validación usuario existe y más

1 - ¿donde creas el XMLHttpRequest?

2 - validas if(http.readyState == 4) pero te falta también if(http.status == 200) (HTTP OK)

3 - para evitar el submit de los formularios por teclear enter en caso de AJAX, se coloca en el onsubmit del form que retorne false:

<form onsubmit="return false;" ... /> ... </form>
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...
  #3 (permalink)  
Antiguo 01/05/2011, 06:11
 
Fecha de Ingreso: abril-2011
Mensajes: 2
Antigüedad: 13 años
Puntos: 0
Respuesta: Formulario Ajax+PHP con validación usuario existe y más

Cita:
Iniciado por maycolalvarez Ver Mensaje
1 - ¿donde creas el XMLHttpRequest?

2 - validas if(http.readyState == 4) pero te falta también if(http.status == 200) (HTTP OK)

3 - para evitar el submit de los formularios por teclear enter en caso de AJAX, se coloca en el onsubmit del form que retorne false:

<form onsubmit="return false;" ... /> ... </form>
Buenas, gracias por contestar.
A ver, no te he puesto TODO el código, solo la parte importante. Lo demás está ok, no hay problema. Lo del http.status == 200 también lo tengo contemplado, tienes razón en eso.
Por lo demás creo que no entiendo el concepto de cómo lo hago para que el botón submit verifique si todos los campos han sido correctamente rellenados, porque cada campo se rellena y se comprueba individualmente, pero tengo que hacer que el botón submit lo sepa.
Ahi es dónde no se como hay que hacerlo.. Si me puedes ayudar con eso.. gracias de nuevo!
  #4 (permalink)  
Antiguo 02/05/2011, 16:11
Avatar de maycolalvarez
Colaborador
 
Fecha de Ingreso: julio-2008
Ubicación: Caracas
Mensajes: 12.120
Antigüedad: 15 años, 9 meses
Puntos: 1532
Respuesta: Formulario Ajax+PHP con validación usuario existe y más

para eso tienes el evento onsubmit del form, cuando haces click en un input type="submit" el mismo desencadena el evento de envío de form.
__________________
¡Por favor!: usa el highlight para mostrar código
El que busca, encuentra...

Etiquetas: ajax, php+ajax+formularios
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:13.