Form validation php and ajax

Asked

Viewed 1,631 times

2

Sorry if the question is silly, but I don’t know much about ajax and I’m trying to make a basic form to test the validation using ajax and php (if possible). Good reading on the internet and seeing some articles, so far I arrived with the code below, but it is not working. I want that when the person is typing or when sending the form he does the validation in php and if there are any errors he returns using the error ajax.

*The ini.php file is my connection to the database, I did not query because, first I would like to test the errors and then send the data to the database. And I didn’t put in any other input so I wouldn’t complicate it by solving one.

Thank you.

HTML:

  <table>
    <tr>
      <td><input type="text" name="nome" placeholder="Nome" maxlength="20" onBlur="Validate(this.value)"></td>
       <span id="error"><?php echo $error; ?></span>
    </tr>  
  </table>

"Ajax":

    function Validate(data){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
            document.getElementById('error').innerHTML = xmlhttp.responseText;  
        }   
    };
    xmlhttp.open("GET", "register.php?q=" + data, true);
    xmlhttp.send();

    }

PHP:

$error = array(
    "Nome é obrigatório.",
    "Somente 20 caracteres são permitidos.",
    "Somente letras e espaços são permitidas."
);

// Get the q parameter from url
$q = $_REQUEST["q"];

if($_SERVER["REQUEST_METHOD"] === "POST"){
    if(empty($q)){
        echo $error[0]; 
    } else if(!preg_match("/^[a-zA-Z]*$/", $q)){
        echo $error[2];
    } else if(strlen($q) > 20){
        echo $error[1];
    }
}

?>

  • You can use Pure Jquery or JS ?

  • Yes, more I know validate using Jquery or JS, I would really like to validate, using Ajax, thanks

  • You will not validate using ajax, or validate on the client side (javascript), or on the server side (php, recommended)

  • Take a look at my answer here: http://answall.com/questions/142834/enviando-uma-imagem-e-outros-dados-via-jquery-para-php/142858#142858 . Then I validated the server side

  • Thanks for the tip

  • You got an idea of how to do it?

Show 1 more comment

1 answer

1


You should always validate on the server, for security reasons (My opinion). In the case of Ajax, it is more so the page does not need to reload when giving a return to the user.

Following your example I made one here, so you can adapt.

Note that I removed the maxlength="20", because this way it does not allow the user to add more than 20 characters (this to be able to use the back-end validation). In your case data was not receiving the value of input, so I added:

var data = document.getElementById("data_id").value;

And I added that value through a id input, could be otherwise.

 <table>
    <tr>
    <form method="GET" action="register.php">   
      <td><input type="text" name="data_input" id="data_id" placeholder="Nome" ></td>
      <td><input type="submit" value="submit"  name="submit" onclick="Validate();return false;"></td>
       <span id="error"></span>
    </form>
    </tr>  
  </table>
  <script>
    function Validate(){
    var data = document.getElementById("data_id").value;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "register.php?data_input=" + data, true);
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
           if(xmlhttp.responseText != "ok!"){
                document.getElementById("data_id").value='';
                document.getElementById("data_id").placeholder = xmlhttp.responseText;
                document.getElementById("data_id").focus();
            }

        } 

    };
    xmlhttp.send();


    }
  </script>

Register.php

if (isset($_GET["data_input"])) {
    $data = $_GET["data_input"];
    if(empty($data)){
      echo "Nome é obrigatório."; 
    } else if(!preg_match("/^[a-zA-Z]*$/", $data)){
      echo "Somente letras e espaços são permitidas.";
    } else if(strlen($data) > 20){
      echo "Somente 20 caracteres são permitidos.";
    }else{
      echo "ok!";
    }
}

I hope I’ve helped, anything comments that adjusts agent.

  • Thank you very much helped!

  • Although in this case I am using the GET method, which is not recommended for sensitive data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.