I m trying to write on a txt file from a form... the idea is that the user press the register button and that will save on a txt file and go back to the index page.
This is my php file:
<?php
if(!empty($_POST)){
$rut = $_POST['rut'];
$dv = $_POST['dv'];
$pnom = $_POST['pnom'];
$snom = $_POST['snom'];
$pape = $_POST['pape'];
$mape = $_POST['mape'];
$sex = $_POST['sex'];
$dir = $_POST['dir'];
$comu = $_POST['comu'];
$pais = $_POST['pais'];
$fono = $_POST['fono'];
$movil = $_POST['movil'];
$mail = $_POST['mail'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpas = $_POST['rpas'];
$usuarios = fopen("usuarios.txt", "a");
fwrite($usuarios, $rut);
fwrite($usuarios,$dv,";");
fwrite($usuarios,$pnom,";");
fwrite($usuarios,$snom,";");
fwrite($usuarios,$pape,";");
fwrite($usuarios,$mape,";");
fwrite($usuarios,$sex,";");
fwrite($usuarios,$dir,";");
fwrite($usuarios,$comu,";");
fwrite($usuarios,$pais,";");
fwrite($usuarios,$fono,";");
fwrite($usuarios,$movil,";");
fwrite($usuarios,$mail,";");
fwrite($usuarios,$user,";");
fwrite($usuarios,$pass,";");
fwrite($usuarios,$rpas,"\r\n");
fclose($usuarios);
}
?>
And this is the form html file:
<html>
<head>
<title>E1Formulario</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="diseno/diseno.css">
</head>
<script language="JavaScript" src="funciones.js"></script>
<body>
<form name="formulario" action="generar_txt.php" method="POST">
<table border="2" align="center" width="50%">
<th colspan="2">FORMULARIO DE INGRESO</th>
<tr>
<td align="left">
Rut:<input name="rut" type="text" size="8">
<select name="dv">
<option value = 0>0</option>
<option value = 1>1</option>
<option value = 2>2</option>
<option value = 3>3</option>
<option value = 4>4</option>
<option value = 5>5</option>
<option value = 6>6</option>
<option value = 7>7</option>
<option value = 8>8</option>
<option value = 9>9</option>
<option value = K>K</option>
</select>
<br><label name="lrut" style="color:#cc0000">*(Campo Obligatorio)</label>
</td>
<td align="left">Primer Nombre:* <input name="pnom" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Segundo Nombre: <input name="snom" type="text"></td>
<td align="left">Apellido Paterno: <input name="pape" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Apellido Materno: <input name="mape" type="text"></td>
<td align="left">
Sexo<br>
Masculino <input name="sex" type="radio" value="Masculino"><br>
Femenino <input name="sex" type="radio" value="Femenino">
<br><label style="color:#cc0000">*(Campo Obligatorio)</label>
</td>
</tr>
<tr>
<td align="left">Dirección: <input name="dir" type="text" size="50"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Comuna: <input name="comu" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">País: <input name="pais" type="text" size="15"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Teléfono: <input name="fono" type="text" size="9" onkeypress="JavaScript: return isNumber(event);"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Movil: <input name="movil" type="text" onkeypress="JavaScript: return isNumber(event);"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Email: <input name="mail" type="text" size="25"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left">Usuario: <input name="user" type="text"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
<td align="left">Contraseña: <input name="pass" type="password"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td align="left" colspan="2">Repetir Contraseña: <input name="rpas" type="password" size="9"><br><label style="color:#cc0000">*(Campo Obligatorio)</label></td>
</tr>
<tr>
<td colspan="2" align="center">
<input class="boton" name="reg" type="button" value="REGISTRAR" onclick="JavaScript: verificar_datos();"/>
</td>
</tr>
</table>
</form>
</body>
This is the function that submit the form to the php file and then goes to the index html file:
function verificar_datos(){
var f = document.formulario;
//Validar que el usuario ingrese todos los campos obligatorios
if(f.rut.value === ""){
alert("El Rut es un campo obligatorio!");
f.rut.focus();
return 0;
}
if(revisarRut(f.rut.value.concat(f.dv.value)) === 0){
return 0;
}
if(f.pnom.value === ""){
alert("El Nombre es un campo obligatorio!");
f.pnom.focus();
return 0;
}
if(f.pape.value === ""){
alert("El Apellido Paterno es un campo obligatorio!");
f.pape.focus();
return 0;
}
if(f.sex.value === ""){
alert("El Sexo es un campo obligatorio!");
f.sex.focus();
return 0;
}
if(f.dir.value === ""){
alert("La Dirección es un campo obligatorio!");
f.dir.focus();
return 0;
}
if(f.comu.value === ""){
alert("La Comuna es un campo obligatorio!");
f.comu.focus();
return 0;
}
if(f.pais.value === ""){
alert("El País es un campo obligatorio!");
f.pais.focus();
return 0;
}
if(revisarTelefonos() === 0){
return 0;
}
if(verificarEmail() === 0){
return 0;
}
if(f.user.value === ""){
alert("Favor ingresar su Usuario");
f.user.focus();
return 0;
}
if(f.pass.value === ""){
alert("Favor Ingrese su Contraseña");
f.pass.focus();
return 0;
}
if(f.rpas.value === ""){
alert("Favor repetir su contraseña en el campo repetir");
f.rpas.focus();
return 0;
}
if(f.rpas.value !== f.pass.value){
alert("La Segunda Contraseña no concuerda");
f.rpas.value = "";
f.rpas.focus();
return 0;
}
f.submit();
alert("DATOS DE USUARIO INGRESADOS EXITOSAMENTE");
window.location= 'index.html';
}
I would be happy if someone could lead me because i think i have everything correct but i still dont get the php to write on txt file.
First, add the follow line, to begin of your PHP File
error_reporting(E_ALL);
Now, change the next line:
$usuarios = fopen("usuarios.txt", "a");
To:
$usuarios = fopen("usuarios.txt", "a+");
The a+ will create a file if not exists.
And, verify if the file is opened.
$usuarios = fopen("usuarios.txt", "a+");
if (!$usuarios) {
die("Could not open file");
} else {
fwrite($usuarios, $rut);
fwrite($usuarios,$dv,";");
fwrite($usuarios,$pnom,";");
fwrite($usuarios,$snom,";");
fwrite($usuarios,$pape,";");
fwrite($usuarios,$mape,";");
fwrite($usuarios,$sex,";");
fwrite($usuarios,$dir,";");
fwrite($usuarios,$comu,";");
fwrite($usuarios,$pais,";");
fwrite($usuarios,$fono,";");
fwrite($usuarios,$movil,";");
fwrite($usuarios,$mail,";");
fwrite($usuarios,$user,";");
fwrite($usuarios,$pass,";");
fwrite($usuarios,$rpas,"\r\n");
fclose($usuarios);
}
Now, everything will work as expected.
Also you should check the file "usuarios.txt" is writable from your webserver user at system like apache or www-user etc. simply check the chmod of the file and the directory
Related
I try to disable a field when an option is chosen in a select. I have created a script with a function in JS to disable it, more however it does not work. Any ideas what to do? When I select "T in% compared to the previous day", I need the "Time /%" field to be disabled, which I have not achieved.
So the code I have implemented for the select is this
Here I create the selectable menu with the fields that they will have and then through a script I pass it to fill the fields and I also create the function to disable the "Hours" boxes. So, here the problem arises, inside the script when const select = document.querySelector (# 'TipoPatron2') is started The table disappears, more however when the query selector is commented the table is still there
<table border="0">
<body>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label>
</td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
<script language="javascript">
let tbody2 = document.querySelector("#mytbody2");
var I = 1;
for (I = 1; I <= 8; I++) {
document.writeln("<tr align=center>");
document.writeln("<td>" + I + " <input type=\"checkbox\" checked id=\"AP2C" + I + "\"></td>");
document.writeln("<td><input type=\"text\" onpaste = \"alerta()\" value=\"0\" id=\"HP2C" + I + "\" maxlength=3 size=3></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"MP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><select name=\"dimado\" id=\"DP2C" + I + "\"><option value =\"0\">0%</option><option value =\"1\">1%</option><option value =\"2\">2%</option><option value =\"3\">3%</option><option value =\"4\">4%</option><option value =\"5\">5%</option><option value =\"6\">6%</option><option value =\"7\">7%</option><option value =\"8\">8%</option><option value =\"9\">9%</option><option value=\"10\">10%</option><option value=\"11\">11%</option><option value=\"12\">12%</option><option value=\"13\">13%</option><option value=\"14\">14%</option><option value = \"15\">15%</option><option value=\"16\">16%</option><option value=\"17\">17%</option><option value=\"18\">18%</option><option value=\"19\">19%</option><option value = \"20\">20%</option><option value=\"21\">21%</option><option value=\"10\">10%</option><option value = \"22\">22%</option><option value = \"23\">23%</option><option value = \"24\">24%</option><option value = \"25\">25%</option><option value = \"26\">26%</option><option value = \"27\">27%</option><option value = \"28\">28%</option><option value = \"29\">29%</option><option value = \"30\">30%</option><option value = \"31\">100%</option></select></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"IP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("<td><input type=\"text\" value=\"0\" id=\"CP2C" + I + "\" maxlength=2 size=2></td>");
document.writeln("</tr>");
}
//Creo una selector para que valide si se selecciona la opción de "T%" se ejecute la función desactivar
/*const select = document.querySelector('#TipoPatron2')
select.onchange = () => {
if (select.value == '10') {
desact()
}
}
*/
//Se crea la función alerta para cuando se haga un pegado en los box se ejecute la alerta
function alerta() {
alert("Seguro que quieres actualizar?");
}
//Se crea una función desactivar que se efectua en un for de 0 a 8 con el ID de las horas
function desact() {
for (let i = 1; i <= 8; i++)
document.getElementById('HP2C' + i).setAttribute("disabled", "disabled");
}
</script>
<tr align="center">
</tbody>
</table>
</body>
</td>
Photos when when queryselector is not commented
Now, I go to the page and the table disappears enter image description here
And if I comment the const select = document.querySelector ('# TipoPatron2') the table appears enter image description here
I need this query selector, since this is in charge of disabling the "Hora/%" when "T en % respecto día anterior" is selected in the first select. Any ideas what to do pls?
Have a look at this
I made the creation of the select simpler
I assume you mean to disable the HP2Cs when TipoPatron2 have value "10"
const tbody2 = document.getElementById("mytbody2");
tbody2.innerHTML = Array.from({length: 8}, (_, index) => index + 1).map(i => `<tr align=center>
<td>${i}<input type="checkbox" checked id="AP2C${i}" /></td>
<td><input type="text" value="0" id="HP2C${i}" maxlength=3 size=3 /></td>
<td><input type="text" value="0" id="MP2C${i}" maxlength=2 size=2 /></td>
<td><select name="dimado" id="DP2C ${i}">${Array.from({length: 29}, (_, index) => index + 1).map(i => `<option value="${i}">${i}%</option>`).join("") }
<option value = "31">100%</option></select></td>
<input type="text" value="0" id="IP2C${i}" maxlength=2 size=2 /></td>
<td><input type="text" value="0" id="CP2C${i}" maxlength=2 size=2 /></td>
</tr>`).join("")
const HP2Cs = document.querySelectorAll("[id^=HP2C]")
document.getElementById("TipoPatron2").addEventListener("change", function() {
const dis = this.value==="10";
HP2Cs.forEach(hp2c => hp2c.disabled = dis)
})
tbody2.addEventListener("paste", e => {
const tgt = e.target;
if (tgt.id.startsWith("HP2C")) alert("Seguro que quieres actualizar?");
})
<table border="0">
<tbody>
<tr>
<td><strong>Patrón 2</strong>(
<select name="TipoPatron2" id="TipoPatron2">
<option value="00">T desde el encendido</option>
<option value="01" selected="selected">T desde las 12:00</option>
<option value="10">T en % respecto día anterior</option>
</select>)</td>
<td><input type="button" onclick="changeP2();" value="Actualizar"> <label id="Error2" style="color: red"></label></td>
</tr>
<tr>
<td>
<table>
<thead>
<tr color="#ccff00">
<td>Cambio</td>
<td>Hora/%</td>
<td>Minutos</td>
<td>Dimado</td>
<td>Dimado Entrada</td>
<td>Color</td>
</tr>
</thead>
<tbody id="mytbody2">
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
I have a signup form, and I would like to verify it before entering the data in the database.
Verify if the phone number is all numeric, then compare the username in the database to see if it is already existing, and if it's all good, register in the database.
At first, I was using this :
<?php
session_start();
include("connection.php");
include("fonctions.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//Récupérer les data de la variable post
$prenom = $_POST['txtPrenom'];
mysqli_real_escape_string($con,$prenom);
$nom = $_POST['txtNom'];
mysqli_real_escape_string($con,$nom);
$adresseMail = $_POST['txtAdresseMail'];
mysqli_real_escape_string($con,$adresseMail);
$numeroGSM = $_POST['txtGSM'];
mysqli_real_escape_string($con,$numeroGSM);
$identifiant = $_POST['txtIdentifiant'];
mysqli_real_escape_string($con,$identifiant);
$motDePasse = $_POST['txtMotDePasse'];
mysqli_real_escape_string($con,$motDePasse);
$refClient = random_num(20);
mysqli_real_escape_string($con,$refClient);
$invite = 0;
mysqli_real_escape_string($con,$invite);
if (!empty($prenom) && !empty($nom) && !empty($adresseMail) && !empty($numeroGSM) && !empty($identifiant) && !empty($motDePasse))
{
if (!is_numeric($numeroGSM))
{
//alert("Numéro de GSM invalide");
}
else
{
$identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".$identifiant."' ";
$result = mysqli_query($con, $identifiantPresent);
if (mysqli_num_rows($result) > 0)
{
alert("Identifiant existe déjà");
}
else
{
//Enregistrement dans la base de données
$query = "insert into tblclient(refClient,prenom,nom,adresseMail,numeroGSM,identifiant,motDePasse,invite) values ('$refClient','$prenom','$nom','$adresseMail','$numeroGSM','$identifiant','$motDePasse','$invite')";
mysqli_query($con, $query);
alertHeader("Compte crée avec succès","../index.php");
}
}
}
else
{
alert("Veuillez remplir tout les champs");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>La Cour des Dames</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="/CSS/StyleAccueil.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div id="Contenaire">
<header id="FondBanniere">
<img src="../Images/Logo.jpeg" id="Banniere">
</header>
<link href="../CSS/StyleAccueil.css" rel="stylesheet" />
<div class="persoNav">
<ul class="nav justify-content-center">
<li class="nav-item">
<button id="btnAccueil" class="nav-link">Accueil</button>
</li>
</ul>
</div>
<form method="post">
<table class="tableauInscription">
<tr>
<td colspan="2"><h3 style="text-align:center;">Formulaire d'inscription</h3></td>
</tr>
<tr>
<td class="coteGauche">Prenom :</td>
<td><input type="TextBox" name="txtPrenom" id="txtPrenom" CssClass="form-control" placeholder="Prenom"></td>
</tr>
<tr>
<td class="coteGauche">Nom :</td>
<td><input type="TextBox" name="txtNom" id="txtNom" CssClass="form-control" placeholder="Nom"></td>
</tr>
<tr>
<td class="coteGauche">Adresse email :</td>
<td><input type="email" name="txtAdresseMail" id="txtAdresseMail" CssClass="form-control" placeholder="Adresse email"></td>
</tr>
<tr>
<td class="coteGauche">GSM min 7 :</td>
<td><input type="TextBox" name="txtGSM" id="txtGSM" CssClass="form-control" placeholder="GSM" minlength="7"></td>
</tr>
<tr>
<td class="coteGauche">Identifiant :</td>
<td><input type="TextBox" name="txtIdentifiant" id="txtIdentifiant" CssClass="form-control" placeholder="Identifiant"></td>
</tr>
<tr>
<td class="coteGauche">Mot de passe : </td>
<td><input type="Password" name="txtMotDePasse" id="txtMotDePasse" CssClass="form-control" placeholder="Mot de passe"></td>
</tr>
<tr>
<td class="coteGauche"></td>
<td style="padding-left:33px; padding-top:10px; padding-bottom:10px;">
<button type="submit" id="btnCreerCompte" class="btn btn-dark">Créer le compte</button></td>
</tr>
</table>
</form>
</body>
<!-- PARTIE SCRIPT -->
<script type="text/javascript">
document.getElementById("btnAccueil").onclick = function () {
location.href = "../index.php";
};
</script>
</html>
But the problem was the page was refreshing after an alert was display, so I search for that and i found the " onsubmit", but now the problem is that I need to do all of this in my function :
<?php
session_start();
include("connection.php");
include("fonctions.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>La Cour des Dames</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="/CSS/StyleAccueil.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script type="text/javascript">
function valide_GSM() {
var prenom = document.getElementById("txtPrenom").value;
var nom = document.getElementById("txtNom").value;
var mail = document.getElementById("txtAdresseMail").value;
var numGSM = document.getElementById("txtGSM").value;
var identifiant = document.getElementById("txtIdentifiant").value;
var motDePasse = document.getElementById("txtMotDePasse").value;
if (!empty(prenom) && !empty(nom) && !empty(adresseMail) && !empty(numeroGSM) && !empty(identifiant) && !empty(motDePasse))
{
if (isNaN(numGSM))
{
alert("Numéro de gsm non valide");
//Phone number invalid
document.getElementById("txtGSM").focus();
return false;
}
else
{
identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".identifiant."' ";
result = mysqli_query(con, identifiantPresent);
if (mysqli_num_rows(result) > 0)
{
alert("Identifiant existe déjà");
//Username already existing
}
else
{
//Enregistrement dans la base de données
//Registration in the database
query = "insert into tblclient(refClient,prenom,nom,adresseMail,numeroGSM,identifiant,motDePasse,invite) values ('refClient','prenom','nom','adresseMail','numeroGSM','identifiant','motDePasse','invite')";
mysqli_query(con, query);
alertHeader("Compte crée avec succès","../index.php");
//Account created successfully
}
}
}
else
{
alert("Veuillez remplir tout les champs");
//Please fill all input box
}
return true;
}
</script>
</head>
<body>
<div id="Contenaire">
<header id="FondBanniere">
<img src="../Images/Logo.jpeg" id="Banniere">
</header>
<link href="../CSS/StyleAccueil.css" rel="stylesheet" />
<div class="persoNav">
<ul class="nav justify-content-center">
<li class="nav-item">
<button id="btnAccueil" class="nav-link">Accueil</button>
</li>
</ul>
</div>
<form method="post" onsubmit="return valide_GSM();">
<table class="tableauInscription">
<tr>
<td colspan="2"><h3 style="text-align:center;">Formulaire d'inscription</h3></td>
</tr>
<tr>
<td class="coteGauche">Prenom :</td>
<td><input type="TextBox" name="txtPrenom" id="txtPrenom" CssClass="form-control" placeholder="Prenom"></td>
</tr>
<tr>
<td class="coteGauche">Nom :</td>
<td><input type="TextBox" name="txtNom" id="txtNom" CssClass="form-control" placeholder="Nom"></td>
</tr>
<tr>
<td class="coteGauche">Adresse email :</td>
<td><input type="email" name="txtAdresseMail" id="txtAdresseMail" CssClass="form-control" placeholder="Adresse email"></td>
</tr>
<tr>
<td class="coteGauche">GSM min 7 :</td>
<td><input type="TextBox" name="txtGSM" id="txtGSM" CssClass="form-control" placeholder="GSM" minlength="7"></td>
</tr>
<tr>
<td class="coteGauche">Identifiant :</td>
<td><input type="TextBox" name="txtIdentifiant" id="txtIdentifiant" CssClass="form-control" placeholder="Identifiant"></td>
</tr>
<tr>
<td class="coteGauche">Mot de passe : </td>
<td><input type="Password" name="txtMotDePasse" id="txtMotDePasse" CssClass="form-control" placeholder="Mot de passe"></td>
</tr>
<tr>
<td class="coteGauche"></td>
<td style="padding-left:33px; padding-top:10px; padding-bottom:10px;">
<button type="submit" id="btnCreerCompte" class="btn btn-dark">Créer le compte</button></td>
</tr>
</table>
</form>
</body>
<!-- PARTIE SCRIPT -->
<script type="text/javascript">
document.getElementById("btnAccueil").onclick = function () {
location.href = "../index.php";
};
</script>
</html>
And obviously this doesn't work, but I'm a little stuck, I don't know how to adapt or where to look for my research. Thank you all for your attention.
I think you used the wrong variable names. For example, in your JS (IF statement), the variable is mail instead of adresseMail. Correct those variables and then try once.
Also, in your function, whenever you are displaying alert for invalid fields or any fields, just add return false. This will ensure that the processing stops and the function does not return true by default when there's an error.
Here's the changes:
var mail = document.getElementById("txtAdresseMail").value; // rename to adresseMail
var numGSM = document.getElementById("txtGSM").value; // rename to numeroGSM
...
...
else
{
alert("Veuillez remplir tout les champs");
//Please fill all input box
return false; // ADD THIS
}
Keep your JavaScript separate from your PHP code to make it more readable.
Here is a sample Ajax code. You'll need another php check-user.php to check if user existed.
Note:
Try using Ajax, start from simple. It can improve overall user experience. AJAX allows you to do checks with the server without refreshing the page. Try this simple example. But note that users can disable javascript, so it's always a good idea to validate forms both in client and server side, just maintain your php validation.
Beware that your code is wide open to SQL Injections. You should use parameterized prepared statements instead. Check this out.
Form Validation with JQuery and Ajax in mainForm.php
$('#btnCreerCompte').on('click',function(e){
//prevent submitting form
e.preventDefault();
//Get Input Values
var prenom = document.getElementById("txtPrenom").value;
var nom = document.getElementById("txtNom").value;
var mail = document.getElementById("txtAdresseMail").value;
var numGSM = document.getElementById("txtGSM").value;
var identifiant = document.getElementById("txtIdentifiant").value;
var motDePasse = document.getElementById("txtMotDePasse").value;
//Form Validation
if (prenom && nom && mail && numGSM && identifiant && motDePasse){
if (isNaN(numGSM)){
alert("Numéro de gsm non valide");
//Phone number invalid
document.getElementById("txtGSM").focus();
return false;
}
else{
//Call Ajax to check if user existed
$.ajax({
type : "POST",
url : "check-user.php",
dataType: "json",
data: {
//data you need for php query, to check if user existed
//Use $_POST['identifiant'] in check-user.php
identifiant: identifiant
},
success:function(result) {
// alert(result.msg);
if (result.msg == "Success"){
e.preventDefault();
//Submit form if user not existed
$('form').submit();
}
else if (result.msg == "Failed"){
e.preventDefault();
alert("User Existed!");
}
}
});
}
}
else{
alert("Veuillez remplir tout les champs");
return false;
}
});
PHP: check-user.php
<?php
//DB Connection
$con = ..;
$identifiant = $_POST['identifiant'];
$identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".$identifiant."' ";
$result = mysqli_query($con, $identifiantPresent);
if (mysqli_num_rows($result) > 0){
$arr = array('msg' => "Failed");
}
else{
$arr = array('msg' => "Success");
}
echo json_encode($arr);
?>
I have a sign up form where I have taken some basic details of the customer and a Submit button.
I have validate all the fields using ajax but confirm password field using javascript. When I write code only using Ajax and not validating Confirm password field it is running perfectly but the problem is when I am validation it using JS submit button is not getting enable.
Sign up form:
<html>
<head>
<title> Registration Form </title>
<script language="javascript">
var flag = false;
function validate(element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new Activexobject("Microsoft.XMLHTTP");
}
var myField = element;
xmlhttp.open('GET', 'validate.php?' + myField.id + "=" + myField.value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
//alert("Hello");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var response = xmlhttp.responseText.split("||");
//alert("H2");
}
var divname = "err" + myField.id.substring(3);
var mydiv = document.getElementById(divname);
if (!eval(response[0]))
{
//alert("Fail");
//alert("Value: "+response);
mydiv.innerHTML = response[1];
myField.valid = false;
}
else
{
//alert("Success");
myField.valid = true;
mydiv.innerHTML = "";
}
var btn = document.getElementById("btnSubmit");
btn.disabled = !isValidForm();
}
}
;
function password()
{
var pass = document.getElementById("txtpswd").value;
var Confirm_pass = document.getElementById("txtConfirmpassword").value;
alert("Pass " + pass);
alert("Confirm: " + Confirm_pass);
if (pass == Confirm_pass)
{
flag = true;
alert("True");
document.getElementById("errConfirmpassword").innerHTML = "";
}
else
{
alert("False");
flag = false;
document.getElementById("errConfirmpassword").innerHTML = "Password does not Match";
}
}
;
function isValidForm()
{
var f1 = document.getElementById("txtfname");
var f2 = document.getElementById("txtlname");
var f3 = document.getElementById("txtaddress");
var f4 = document.getElementById("txtzip");
var f5 = document.getElementById("txtnumber");
var f6 = document.getElementById("txtmail");
var f7 = document.getElementById("txtpswd");
var f8 = document.getElementById("txtConfirmpassword");
return(f1.valid && f2.valid && f3.valid && f4.valid && f5.valid && f6.valid && f7.valid && f8.valid);
}
;
</script>
</head>
<body>
<center>
<h1><font color="red"> New User Registration Form </font></h1>
<form name="SignUpForm" method="POST" action="function_customer.php?val=insert">
<table>
<tr>
<td id=q> <font face="Century Schoolbook"> First Name :</font></td> <br>
<td> <input type=text name=txtfname id="txtfname" placeholder=First_name onchange="validate(this);" valid=false> </td>
<td><div id="errfname"/></td>
</tr>
<tr>
<td id=q> Last Name :</td>
<td> <input type=text name=txtlname id="txtlname" placeholder=Last_Name onchange="validate(this);" valid=false> </td>
<td><div id="errlname"/></td>
</tr>
<tr>
<td id=q>Address : </td><br>
<td> <textarea rows=5 cols=20 name="txtaddress" id="txtaddress" onchange="validate(this);" valid=false>
</textarea>
</td>
<td><div id="erraddress"/></td>
</tr>
<tr>
<td id=q> Contact no : </td>
<td> <input type=text name="txtnumber" id="txtnumber" onchange="validate(this);" valid=false> </td>
<td><div id="errnumber"/></td>
</tr>
<tr>
<td id=q> Gender </td>
<td> <select name="txtcity" id="gender">
<option value="Male"> Male </option>
<option value="Female"> Female </option>
</select>
</td>
</tr>
<tr>
<td id=q> City </td>
<td>
<select name="txtcity" id="txtcity">
<option> City </option>
<option value="Vadodara"> Vadodara </option>
<option value="Ahmedabad"> Ahmedabad </option>
<option value="Surat"> Surat </option>
<option value="Rajkot"> Rajkot </option>
<option value="Bhavnagar">Bhavnagar</option>
<option value="Jamnagar">Jamnagar</option>
<option value="Nadidad">Nadidad</option>
<option value="Morvi">Morvi</option>
<option value="Gandhidham">Gandhidham</option>
<option value="Adipur">Adipur</option>
<option value="Anand">Anand</option>
<option value="Baruch">Baruch</option>
<option value="Godhra">Godhra</option>
<option value="Veraval">Veraval</option>
<option value="Navsari">Navsari</option>
</select>
</td>
</tr>
<tr>
<td id=q> ZIP : </td>
<td> <input type=text name=txtzip id="txtzip" onchange="validate(this);" valid=false> </td>
<td><div id="errzip"/></td>
</tr>
<tr>
<td id=q> Email Id : </td>
<td> <input type="email" name=txtmail placeholder=someone#exe.com id="txtmail" onchange="validate(this);" valid=false> </td>
<td><div id="errmail"/></td>
</tr>
<tr>
<td id=q> New Password : </td>
<td> <input type="password" name="txtpswd" id="txtpswd" onchange="validate(this);" valid=false>
</td>
<td><div id="errpswd"/></td>
</tr>
<tr>
<td id=q>Confirm Password : </td><td><input type="password" name=txtConfirmpassword id="txtConfirmpassword" onchange="password();" valid=false>
</td>
<td><div id="errConfirmpassword"/></td>
</tr>
<tr>
<td></td><td><input type=reset name=reset value=Reset>
</td>
</tr>
<tr>
</tr>
</table>
</form>
<br>
<br>
<br>
<br><br>
</center>
</body>
</html>
What should I do to validate all the fields and enabling the Submit Button?
First of all I suggest you read up on the latest HTML elements and use CSS for centering or styling your elements and avoid usage of obsolete elements like <font> and <center>.
Having said that, the issue in your code is that you're not calling validate() to check if the form is valid after password & confirm password fields match, so change your password() like below.
function password(){
var btn = document.getElementById("btnSubmit");
var pass = document.getElementById("txtpswd").value;
var confirm_pass = document.getElementById("txtConfirmpassword").value;
var pwdErrorElement = document.getElementById("errConfirmpassword");
if (pass === confirm_pass){
flag = true;
pwdErrorElement.innerHTML = "";
btn.disabled = !isValidForm();
}else{
flag = false;
pwdErrorElement.innerHTML = "Password does not Match";
btn.disabled = true;
}
}
Also I suggest you to make use of value property on each field to do the validations on client side rather than making a server call for every field change. You can use field values for validations by changing the last statement in your isValidForm() like below.
function isValidForm(){
// get all the field references
return(f1.value && f2.value && f3.value && f4.value
&& f5.value && f6.value && f7.value && f8.value);
}
Once you're done with the JS validations, you can enable the submit button and do validations for all fields at once on your server side on form submit. I mean that's the very purpose of doing client side validations using JS. You don't want to ask for feedback (valid or not) for every field change.
Here's a working Pen with all the above changes.
Hi and sorry for my bad English
I have a contact page and i am using javascript to make a "captcha". so peaople must make a math and if thats correct they can send me a e-mail. Now my problem is that javasctipt give a alert that the math is wrong or not filled but the e-mail is still seended.
my html:
<script type="text/javascript">
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
function randNums () {
var rand_num1 = Math.floor(Math.random()*10)+1;
var rand_num2 = Math.floor(Math.random()*10)+1;
document.getElementById("digit1") .innerHTML=rand_num1;
document.getElementById("digit2") .innerHTML=rand_num2;
}
</script>
<body onload="randNums() ;">
<form action="/cgi-bin/form.cgi" method="POST" onsubmit="return validate ();">
<input type="hidden" name="DEBUG" value="0">
<input type="hidden" name="MAILFILE" value="peymankarimi/form/sjabloon.txt">
<input type="hidden" name="MAILTO" value="peyman_50#hotmail.com">
<input type="hidden" name="REPLYFAULT" value="peymankarimi/form/formulier.html">
<input type="hidden" name="REPLYOK" value="peymankarimi/form/verzonden.html">
<table border="0" width="374" id="contactformulier">
<tr>
<td width="137">Naam:</td>
<td width="230"><input type="text" size="31" name="naam" placeholder="Naam"></td>
</tr>
<tr>
<td width="137">Voornaam:</td>
<td width="230"><input type="text" size="31" name="voornaam" placeholder="Voornaam"></td>
</tr>
<tr>
<td width="137">Woonplaats:</td>
<td width="230"><input type="text" size="31" name="woonplaats" placeholder="Woonplaats"></td>
</tr>
<tr>
<td width="137">Telefoonnummer:</td>
<td width="230"><input type="text" size="31" name="telefoon" placeholder="Telefoonnummer"> </td>
</tr>
<tr>
<td width="137">E-mailadres: <br></br></td>
<td width="230">
<input type="text" size="31" name="MAILFROM" placeholder="E-mailadres"> <br></br> </td>
</tr>
</tr>
<tr>
<td width="137">Onderwerp:</td>
<td width="230"><input type="text" size="31" maxlength="30" name="SUBJECT"> </td>
</tr>
<tr>
<td colspan="2">Uw vragen, opmerkingen, suggesties, ... :<br>
<textarea id="ta" name="omschrijving" rows="6" cols="43" ></textarea>
<br />
<strong> Tel deze cijfers op </strong>
<span id="digit1"> </span> +
<span id="digit2"> </span> =
<input type="text" id="answer" size="2"; />
<br />
<p align="right"><input type="submit" name="cmdVerzenden" value="Verzenden">
<input type="reset" name="cmdWissen" value="Wissen"></td>
</form>
</tr>
</table>
</form>
</body>
Your validate function needs to return false on all errors to stop the form from submitting. You only seem to have it for one error.
function validate () {
var ta = document.getElementById("ta").value;
var answer = document.getElementById("answer").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1+ digit2;
if (answer === null || answer === "") {
alert("reken de cijfers uit");
return false;
} else if (answer != sum){
alert("je som is fout");
return false;
} else if (ta === null || ta === ""){
alert("schrijf een bericht");
return false;
} else {
document.getElementById("answer").innerHTML = "bezig met sturen";
document.getElementById("answer").innerHTML = "";
}
}
I need to do a very basic form validation, and my method of choice is jQuery. However, for some reason, the validation function seems not to get fired at all.
After looking at this for several hours I can't find out what the problem is.
HTML:
<form id="form1" name="form1" method="post" action="process.php">
<table width="100%" border="0" cellspacing="5" cellpadding="0">
<tr>
<td width="160">Meno:</td>
<td><input type="text" name="meno" id="meno" /></td>
<td width="160">Priezvisko:</td>
<td><input type="text" name="priezvisko" id="priezvisko" /></td>
</tr>
<tr>
<td width="160">Názov spolocnosti: <br />
<span class="register_comment">(nevyplnajte ak nie ste podnikatel)</span></td>
<td><input type="text" name="spolocnost" id="spolocnost" /></td>
<td width="160">Krajina:</td>
<td><select name="krajina" id="krajina">
<option value="" selected="selected"> </option>
<option value="cz">Ceská republika</option>
<option value="sk">Slovenská republika</option>
</select></td>
</tr>
<tr>
<td width="160">Adresa:</td>
<td><input type="text" name="adresa" id="adresa" /></td>
<td width="160">Mesto:</td>
<td><input type="text" name="mesto" id="mesto" /></td>
</tr>
<tr>
<td width="160">Email:<br />
<span class="register_comment">(na tento email Vám príde potvrdenie)</span></td>
<td><input type="text" name="email" id="email" /></td>
<td width="160">Telefonický kontakt:<br />
<span class="register_comment">(uvádzajte kontakt na mobilný telefón na ktorom budete zastihnutelní najmä 10.10.!)</span></td>
<td><input type="text" name="telefon" id="telefon" /></td>
</tr>
<tr>
<td width="160">Miesto nástupu: </td>
<td colspan="3"><select name="nastup" id="nastup">
<option value="" selected="selected"> </option>
<option value="nr">Nitra</option>
<option value="ba">Bratislava</option>
<option value="br">Brno - Avion Shopping Park, Škandinávská 128/2</option>
<option value="ph">Praha - Avion Shopping Park, Škandinávská 15/A</option>
<option value="pl">Plzen - OC Olympia, Písecká 972/1</option>
</select></td>
</tr>
<tr>
<td colspan="4"><p>
<label>
<input type="checkbox" name="suhlas" value="checkbox" id="suhlas" />
Oboznámil som sa s podmienkami úcasti a Súhlasím s podmienkami úcasti </label>
FLEX Polishing Camp<br />
</p></td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" id="button" value="Odoslat záväznú prihlášku na FLEX Polishing Camp" style="width:500px;" /></td>
</tr>
<tr>
<td colspan="4" class="register_comment">xxxx</td>
</tr>
</table>
</form>
jQuery:
<script>
$("#form1").submit(function() {
var errors = new array();
if ($('input[name=meno]').val() == "") {
errors.push('Meno je povinná položka.');
}
if ($('input[name=priezvisko]').val() == "") {
errors.push('Priezvisko je povinná položka.');
}
if ($('input[name=krajina]').val() == "") {
errors.push('Je nutné vybrať si krajinu - ČR alebo SR.');
}
if ($('input[name=adresa]').val() == "") {
errors.push('Adresa je povinná položka.');
}
if ($('input[name=mesto]').val() == "") {
errors.push('Mesto je povinná položka.');
}
if ($('input[name=email]').val() == "") {
errors.push('Email je povinná položka.');
}
if ($('input[name=telefon]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if ($('input[name=nastup]').val() == "") {
errors.push('Telefonický kontakt je povinná položka.');
}
if (!$('#suhlas').attr('checked')) {
errors.push('Je potrebné vysloviť súhlas s podmienkami zaškrtnutím tlačítka "Oboznámil som sa s podmienkami účasti a Súhlasím s podmienkami účasti FLEX Polishing Camp".');
}
if ( errors.lenght > 0 )
{
var text;
for (var i = 0; i < errors.length; i++) {
text = text + errors[i] + '\n';
};
alert(text);
return false;
}
return true;
});
</script>
$("form1") should be $("#form1")
As other mention you have missed the # for your ID selector, you can also use map method and minify your code.
$("#form1").submit(function() {
var errors = [];
errors = $('input[type=text]', this).filter(function(){
return $.trim(this.value) == "";
}).map(function() {
return this.name + ' je povinná položka.';
}).get();
if (errors.length) {
var text = errors.join('\n');
alert(text);
return false;
}
});
http://jsfiddle.net/bwVWQ/
First $("form1") should be $("#form1")
//Secondly
text = text + arr[i] + '\n';
//Should be
text = text + errors[i] + '\n'; OR text += errors[i] + '\n';
Looks like the Updated code has again a typo in it..
This might be preventing it
if ( errors.lenght > 0 ) // Supposed to be errors.length
You are missing the # sign on your selector, #form1
$("#form1").submit(function() {