PHP, JS i AJAX forma?

PHP, JS i AJAX forma?

offline
  • Pridružio: 06 Jan 2011
  • Poruke: 4

Napravio sam malu test formu za pocetak (samo 2 polja i 1 dugme) cisto da probam da ukapiram kako radi...medutim naisao sam na problem sledece prirode:
Forma funkcionise pristojno u smislu - kada kliknem na polja a ne unesem nista, ona se lepo oboje u crveno, ili kada unesem ispravne podatke u polja, ona se oboje u zeleno...problem je u tome sto kada kliknem na "submit" (bez ikakve interakcije sa poljima-kliktanja na njih, unosa ili sl.), prodje validacija korektno, a to zelim da izbegnem! Dakle, voleo bih da ako korisnik ostavi prazna polja i lupi "submit", da se odradi validacija na svim poljima i da se ona neispravna ofarbaju u crveno...Nadam se da neko moze da pomogne...

Evo koda:

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head>  <title>Test Forma</title>  <script src="validate.js" type="text/javascript"></script>  <link rel="stylesheet" href="style.css" type="text/css" media="screen">  <link rel="SHORTCUT ICON" href="/favicon.ico"> </head> <body> <form name="vform" id="vform" method="get" action="index.html">  <label for="username">Username: </label>  <input type="text" name="username" id="username" class="required,username" autocomplete="off">&nbsp;     <img width="16" height="16" name="username" src="img/blank.gif" alt="">    <span class="expl">only characters, like abcd</span>  <br />  <label for="password">Password: </label>  <input type="text" name="password" id="password" class="required,password" autocomplete="off">&nbsp;     <img width="16" height="16" name="password" src="img/blank.gif" alt="">    <span class="expl">numbers and/or characters, like 123abc</span>  <br />  <br />  <input type="submit" name="submit" id="submit" value="Submit"> </form> </body> </html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

validate.js

// Load the getForm function while page is loading window.onload = getForm; // Set this to your validation PHP script, default is "validate.php?value=" var vUrl = "validate.php?value="; // Set this to your form's id var formid = "vform"; // This is the array for error handling var vError =  [];                 // We attach to every input field a little js function getForm() {            // Important: Our form has to got the "vform" id    var form = document.getElementById(formid);    if (document.getElementsByTagName) {       var vInput = document.getElementsByTagName("input");       for (var vCount=0; vCount<vInput.length; vCount++)          vInput[vCount].onblur = function() { return validateIt(this); }              }     } // Refers to the function http = getHTTPObject(); function getHTTPObject() {   var xmlhttp;     /*@cc_on     @if (@_jscript_version >= 5)     try {       xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");     }catch(e){       try{       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");     }catch(E){       xmlhttp = false;     }   }   @else     xmlhttp = false;   @end @*/     if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){     try {       xmlhttp = new XMLHttpRequest();     }catch(e){       xmlhttp = false;     }   }     return xmlhttp; } // The main validation-function function validateIt(vInput) {        // Each input field's id    vId = vInput.id;    vValue = vInput.value;    // Separate the class attr of each input field    getValue = vInput.className;    if(getValue.indexOf(",") == -1 ) {       vType = getValue;       vRequired = "";    } else {       vRules = vInput.className.split(",");       vRequired = vRules[0];       vType = vRules[1];    }    // The whole URL    var url = vUrl + (vValue) + "&required=" + (vRequired) + "&type=" + (vType);    // And finally we send it to the url we specified    http.open("GET", url, true);    // The handleHttpResponse is the function we call, when we have an    // answer back from the PHP script    http.onreadystatechange = handleHttpResponse;    http.send(null); } // A function to handle the response from the PHP script function handleHttpResponse() {        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 == "false") {          var sInput = document.getElementById(vId);          var vButton = document.getElementById("submit");          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 == "true") {          var sInput = document.getElementById(vId);                    document[vId].src = "img/true.png";          sInput.style.border = "1px solid #338800";          sInput.style.background = "#c7f7be";          // 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);             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;             }          }       }       if(http.responseText == "none") {          var sInput = document.getElementById(vId);          var vButton = document.getElementById("submit");          document[vId].src = "img/blank.gif";          sInput.style.border = "1px solid #aaa";          sInput.style.background = "#ffffff";          vButton.disabled = false;       }    } }

validate.php

<?php /*  * This is the PHP script to validate the form over AJAX  */ // Start the main function StartValidate(); function StartValidate() {        // Assign some var's for the requests    $required = $_GET["required"];    $type = $_GET["type"];    $value = $_GET["value"];    // This is the function to check if a field is even required or not    // So it's useful if you only want to check if it isn't empty    validateRequired($required, $value, $type);    switch ($type) {       case 'password':          validatePassword($value);          break;       case 'username':          validateUsername($value);          break;           } } // The function to check if a field is required or not function validateRequired($required, $value, $type) {    if($required == "required") {       // Check if we got an empty value       if($value == "") {          echo "false";          exit();       }    } else {       if($value == "") {          echo "none";          exit();       }    } } // I use regular expressions in order to check a field's input, you can // get most of them at the Regex Library at http://www.regexlib.com // There you can check your own regular expressions, too // Validation of characters function validateUsername($value) {    if(ereg("^[a-zA-Z]+$", $value, $regs)) {       echo "true";    } else {       echo "false";    } } // Validation of characters and numbers function validatePassword($value) {    if(ereg("^[a-zA-Z0-9]+$", $value, $regs)) {       echo "true";    } else {       echo "false";    } } ?>



Registruj se da bi učestvovao u diskusiji. Registrovanim korisnicima se NE prikazuju reklame unutar poruka.
offline
  • Pridružio: 21 Apr 2007
  • Poruke: 98

Nemam vremena da gledam ceo kod, ali vidim da ti funkcije nisu baš dobre.

Umesto:
if(ereg("^[a-zA-Z0-9]+$", $value, $regs)) {
Koristi
if (ctype_alnum($value)) {
Za proveru korisničkog imena i lozinke.

[Link mogu videti samo ulogovani korisnici]

Primer:
function validateUsername($value) {    if (ctype_alnum($value)) {       return true;    } else {       return false;    } }

Reši prvo PHP deo koda, pa posle ajax.
Samo znakovi:
[Link mogu videti samo ulogovani korisnici]
Znakovi i brojevi:
[Link mogu videti samo ulogovani korisnici]

Ne treba ti regex za to, pogotovo ereg funkcija koja se više ne koristi.



Ko je trenutno na forumu
 

Ukupno su 1087 korisnika na forumu :: 159 registrovanih, 8 sakrivenih i 920 gosta   ::   [ Administrator ] [ Supermoderator ] [ Moderator ] :: Detaljnije

Najviše korisnika na forumu ikad bilo je 19602 - dana 30 Mar 2026 00:11

Korisnici koji su trenutno na forumu:
Korisnici trenutno na forumu: Adaminho1985, Agape, Aleksandar Šljivar, AleksandarV, aleksjevt, Alen-Delon-u-boji, alex71, amaterSRB, Asteker, Ata81, Avladi, bakos022, Banovo Brdo, Betta, Blizzard035, Bo96, Bobrock1, Boroš, BraneS, Bubili, Burovnyak, ceman, Chainsaw, CikaKURE, Citalac, ClioP1, Colt D, comi991, Crazzer, cvrle312, d.arsenal321, darios, darkkran, Darth Wader, deLacy, delrey, Dimitrije Paunovic, Djole3621, djonsule, DJUNTA, djuradj, Dolinc, DonRumataEstorski, Dr Lobotom, dragan_mig31, draganl, draganst, Dusko_Dugousko, feanor, Giskard, goxin, GrammaticalAnalysis, Grochow, GT, HawX, hyla, ILGromovnik, Ilija84, Imprimatur, Istman, ivan979, Jakonjveliki, Joja, Jovan.D, Jozo74, Još malo pa deda, Kajzer Soze, Kamov, kaput21, Kobrim, koliko, kolle.the.kid, komenski, Koridor, Koča, Kupresko polje, Lep1na, leptirleptir, Lošmi, Lucky 6, LUDI, m0nstrum_, MaCS, Makarid, Malahit, mane123, Manjane, Markobreee, markon1, marsi, mat, matrix_1, max power, mercedesamg, mexo, mgolub, Mickey91, mikki jons, mirkoro, Mldo, Moldovan, moldway, nazgul75, Neutral-M, Nmr, oblivion, Obrenovic, obsidian, ormanj, ostoja, Panter, pceklic, Petarvu, Pewac21, pfc74, pobeda, Poof, prasinar, proka1ng, proljece, rambod, redstar72, Romibrat, royst33, Rupert, Samo gledam, samocitam, SamoGledam, Semberija, Sharpshooter, shiro, shlauf, spektorsky, Srky Boy, stalja, tachinni, tamno.nebo, Tandrkalo, theNedjeljko, Topaz9, Tumansky, Ugljesa99, US_Rank_0, user26, Vanderx, vaso1, vazduh, Veljko™, vlada035, VNVK, Volfero, VPV, Zadonbas, Zastava, zlaya011, zoran77, Zukov, Žrnov, šumar bk2