
Alert si el registro existe en la base de datos al tabular.
#1
Posted 15 October 2012 - 02:52 PM
Tengo un formulario en donde entre otros datos, ingreso números de teléfono y quisiera que al rellenar el campo de número de teléfono y tabular al siguiente campo me diera un mensaje de alerta si existe en la base de datos para no duplicarlo.
Tengo una validación, podría poner la condición en ella?
[js]
function valida_envia(){
//valido el nombre
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
[/js]
Gracias.
#2
Posted 15 October 2012 - 03:15 PM
Saludox !

#3
Posted 15 October 2012 - 03:23 PM
Pero como se haría? soy nuevo en esto y tengo muy pocos conocimientos.
Puede ser con esto, pero como lo integro en la funcion validar?
$sql="SELECT telefono FROM usuarios WHERE telefono='$telefono'";
$res=mysql_query($sql,Conectar::con());
if(mysql_num_rows($res)>=1)
{
echo "<script type='text/javascript'>
alert('El nº de teléfono ya existe');
</script>";
}
else
{
Gracias.
#4
Posted 15 October 2012 - 04:02 PM

#5
Posted 15 October 2012 - 07:41 PM
Como primer paso deberás crear un script en php que reciba como parámetro de entrada el número telefónido y responda si este existe o no... de acuerdo a lo que has hecho esto se haría de la manera:
valida.php
<?php
$telefono = $_REQUEST['telefono'];
sql="SELECT telefono FROM usuarios WHERE telefono='$telefono'";
$res=mysql_query($sql,Conectar::con());
if(mysql_num_rows($res)>=1)
echo "El nº de teléfono ya existe";
?>
Una vez que se tiene el script de php responsable de responder si el teléfono existe crearemos la función en javascript que lo invocará... quedando de la manera:
[js]
//función responsable de crear el objeto para comunicación asíncrona
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
var ajax=nuevoAjax();
ajax.open("GET", "valida.php?telefono="+telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
TelefonoExiste=ajax.responseText;
}
ajax.send(null);
}
function valida_envia(){
//valido el nombre
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
else if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe');
}
else {
//registra el número
}
[/js]
#6
Posted 16 October 2012 - 01:11 AM
[js]<a class="dock-item" onclick="javascript:TelefonoExiste()"><span>Validar</span><img src="imagenes_menu/untitled.png" alt="Validar" /></a>[/js]
Quiero que me haga la funcion TelefonoExiste y la de la validacion pero he debido de hacerlo mal porque no funciona:
He puesto en otro archivo:
valida.php
<?php require_once('Connections/conexion.php'); ?>
<?php
$telefono = $_REQUEST['telefono'];
$sql="SELECT telefono FROM usuarios WHERE telefono='$telefono'";
$res=mysql_query($sql,Conectar::con());
if(mysql_num_rows($res)>=1)
echo "El nº de teléfono ya existe";
?>
y en formulario:
[js]<script language=javascript>
//función responsable de crear el objeto para comunicación asíncrona
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
var ajax=nuevoAjax();
ajax.open("GET", "valida.php?telefono=" telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
TelefonoExiste=ajax.responseText;
}
ajax.send(null);
}
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe');
}
if (document.form1.tecnico.value.length==0){
alert("Selecciona el Técnico")
document.form1.tecnico.focus()
return 0;
}
if (document.form1.situacion.value.length==0){
alert("Selecciona la Situación del Aviso")
document.form1.situacion.focus()
return 0;
}
if (document.form1.FECHA_EMISION.value.length==0){
alert("Selecciona la fecha de emisión del Aviso")
document.form1.FECHA_EMISION.focus()
return 0;
}
if (document.form1.fecha_recepcion.value.length==0){
alert("Selecciona la fecha de recepción del Aviso")
document.form1.fecha_recepcion.focus()
return 0;
}
//el formulario se envia
document.form1.submit();
}
</script>[/js]
Gracias
#7
Posted 16 October 2012 - 07:19 AM
En el archivo "valida.php"
<?php
require_once('Connections/conexion.php');
$telefono = $_REQUEST['telefono'];
$sql="SELECT telefono FROM usuarios WHERE telefono='$telefono'";
$res=mysql_query($sql,Conectar::con());
if(mysql_num_rows($res)>=1)
echo "El nº de teléfono ya existe";
?>
Luego te recomiendo que toda la parte de javascript la coloques en un arhivo funcdin.js
archivo: funcdin.js
[js]
//función responsable de crear el objeto para comunicación asíncrona
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
var ajax=nuevoAjax();
ajax.open("GET", "valida.php?telefono=" telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
TelefonoExiste=ajax.responseText;
}
ajax.send(null);
}
function GuardaFormulario() {
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
else if (document.form1.tecnico.value.length==0){
alert("Selecciona el Técnico")
document.form1.tecnico.focus()
return 0;
}
else if (document.form1.situacion.value.length==0){
alert("Selecciona la Situación del Aviso")
document.form1.situacion.focus()
return 0;
}
else if (document.form1.FECHA_EMISION.value.length==0){
alert("Selecciona la fecha de emisión del Aviso")
document.form1.FECHA_EMISION.focus()
return 0;
}
else if (document.form1.fecha_recepcion.value.length==0){
alert("Selecciona la fecha de recepción del Aviso")
document.form1.fecha_recepcion.focus()
return 0;
}
else if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe');
document.form1.telefono.focus()
return 0;
}
//el formulario se envia
else
document.form1.submit();
}
[/js]
Luego en la página web donde está tu formulario colocarás al inicio:
<HTML>
<HEAD>
<title>el título</title>
<script language="javascript" type="text/javascript" src="funcdin.js"></script>
</HEAD>
Luego entonces en tu botón:
[js]
<a class="dock-item" onclick="GuardaFormulario();">
<span>Validar</span>
<img src="imagenes_menu/untitled.png" alt="Validar"/>
</a>
[/js]
Prueba con esto y si te sigue dando error me dices que mensaje te manda el navegador
#8
Posted 16 October 2012 - 08:04 AM
He recortado un poco las condiciones para no hacerlo pesado:
funcdin.js
[js]
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
var ajax=nuevoAjax();
ajax.open("GET", "valida.php?telefono="+telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
TelefonoExiste=ajax.responseText;
}
ajax.send(null);
}
function GuardaFormulario() {
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
else if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe');
document.form1.telefono.focus()
return 0;
}
//el formulario se envia
else
document.form1.submit();
}
[/js]
Gracias.
#9
Posted 16 October 2012 - 08:20 AM
[js]
//función responsable de crear el objeto para comunicación asíncrona
function nuevoAjax() {
alert('inicando ajax');
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
alert('creamos no ajax');
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
alert('creamos ajax IE');
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
alert('inicia telefono existe');
var ajax=nuevoAjax();
var respuesta = '';
alert('se ha creado ajax');
ajax.open("GET", "valida.php?telefono="+telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
respuesta=ajax.responseText;
alert('Respuesta de php' + respuesta);
TelefonoExiste = respuesta;
}
ajax.send(null);
}
function GuardaFormulario() {
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
else if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe');
document.form1.telefono.focus()
return 0;
}
//el formulario se envia
else
document.form1.submit();
}
[/js]
Por cierto.... modificando el código encontré que tenia un error... en esta línea
ajax.open("GET", "valida.php?telefono=" telefono, true);
deberia ser
ajax.open("GET", "valida.php?telefono="+telefono, true);
#10
Posted 16 October 2012 - 11:24 AM
El error ajax.open("GET", "valida.php?telefono=" telefono, true); esta bien es que no sale el + cuando te lo pongo en la consulta.
Puede ser que falte el ajax.status==200
y me al llegar a la respuesta de php me da el error:
Respuesta de php
<br />
<b>Fatal error</b>: Class 'Conectar' not found in <b>C:\Inetpub\vhosts\xn--electrodiseo-khb.es\httpdocs\Wedserver\valida.php</b> on line <b>9</b><br />
y creo que el error esta el php aquí:
$res=mysql_query($sql,Conectar::con());
Ya esta solucionado

<?php
require_once('Connections/conexion.php');
$telefono = $_REQUEST['telefono'];
$query="SELECT telefono FROM usuarios WHERE telefono='$telefono'";
$result = mysql_query($query);
if(mysql_num_rows($result)>=1)
echo "El nº de teléfono ya existe";
?>
Muchas gracias.
#11
Posted 16 October 2012 - 03:58 PM
if(mysql_num_rows($result)>=1)
Porque puede ser?
#12
Posted 16 October 2012 - 04:05 PM
Saludox !

#13
Posted 16 October 2012 - 04:07 PM
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in......
Gracias.
#14
Posted 16 October 2012 - 04:11 PM

Saludox !

#15
Posted 16 October 2012 - 04:18 PM

Un saludo
#16
Posted 17 October 2012 - 12:49 AM
[js]
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono) {
var ajax=nuevoAjax();
var respuesta = '';
ajax.open("GET", "valida1.php?telefono="+telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
respuesta=ajax.responseText;
alert('Respuesta de php' + respuesta);
TelefonoExiste = respuesta;
}
ajax.send(null);
}
function GuardaFormulario() {
if (document.form1.telefono.value.length==0){
alert("Insertar el Teléfono")
document.form1.telefono.focus()
return 0;
}
else if (TelefonoExiste(document.form1.telefono.value).length==0) {
alert('El nº de teléfono ya existe')
document.form1.telefono.focus()
return 0;
}
//el formulario se envia
else
alert("El formulario se envio con exito!")
document.form1.submit();
}
[/js]
Gracias
#17
Posted 18 October 2012 - 04:05 PM

#18
Posted 18 October 2012 - 04:17 PM
[js]
function nuevoAjax() {
var xmlhttp=false;
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function TelefonoExiste(telefono, _callback) {
var ajax=nuevoAjax();
ajax.open("GET", "valida1.php?telefono=" + encodeURIComponent(telefono), true);
ajax.onreadystatechange=function() {
if ((ajax.readyState==4) && (ajax.status==200)){
//ejecutamos _callback como si fuese una función, pasandole el parámetro
_callback(ajax.responseText);
}
}
ajax.send(null);
}
function GuardaFormulario() {
//usemos mejor las CoLECCIONES, y variables, así ahorramos codigo y lo hace fácil de mantener
var _telefono = document.forms['form1'].elements['telefono'];
if (_telefono.value.length == 0){
alert("Insertar el Teléfono");
_telefono.focus();
return 0;
}
//lamamos a AJAX:
TelefonoExiste(_telefono.value, function(resp) {
//evaluamos la respuesta del server, tengase en cuenta que responseText devuelve un string, por lo tanto hay que parsear a entero si se evalúa un numero:
if (parseInt(resp) == 1) {
//aqui seria bueno un mensaje
alert('el teléfono ya existe');
_telefono.focus();
} else {
//evaluar si se envía el form desde aquí, o se usa ajax para enviarlo.
alert("El formulario se envio con exito!");
document.forms['form1'].submit();
}
});
//como ajax es asincrono, JS NO se detendrá en la llamada anterior, por lo tando hay que retornar false o 0 como lo tienes:
return 0;
}
[/js]
Es que me han ayudado un poco.

#19
Posted 19 October 2012 - 08:38 AM
http://elpoli.delphi...-base-de-datos/
saludox
#20
Posted 19 October 2012 - 10:40 AM
[js]
//función responsable de crear el objeto para comunicación asíncrona
function nuevoAjax() {
var xmlhttp=false;
try {
// Creacion del objeto AJAX para navegadores no IE
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
// Creacion del objet AJAX para IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
xmlhttp=new XMLHttpRequest();
}
}
return xmlhttp;
}
function UsuarioExiste(telefono) {
var existe= "";
var ajax=nuevoAjax();
ajax.open("GET", "valida1.php?telefono="+telefono, true);
ajax.onreadystatechange=function() {
if (ajax.readyState==4)
existe=ajax.responseText;
}
ajax.send(null);
return existe;
}
function validatelefono() {
var telefono = document.getElementById('telefono').value;
if (telefono.length==0){
alert("Por favor, escriba un nº teléfono");
document.getElementById('telefono').focus;
return false;
}
else if (UsuarioExiste(telefono).length > 0) {
alert('El teléfono ya existe');
document.getElementById('telefono').focus;
return false;
}
else {
alert('El teléfono no existe');
document.getElementById('telefono').focus;
return false;
}
}
[/js]
Un saludo