user3173360
user3173360

Reputation:

Form validation and submit ajax

I want to validate my form using ajax, and after it is validated, insert it into the database using ajax.

With this code, it shows the validation messages but it still inserts.

The problem I found is something with the submit button, if I change it into button instead of submit it inserts the form without validation (not even messages) and when I change it back to submit, it also submits the form but it shows the validation messages.

Any idea how to insert after validation? And why it's not working for me?

Thanks

index.php
    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <meta charset="utf-8">
    <title>Form</title>
    </head>
    <script type="text/javascript" src="js/validate.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>


    <body>
    <div id="wrap">
    <table>
    <td>
        <form name="form">
            <tr>
            <p class="names">Voornaam:</p> <p><input type="text" name="voornaam" id="voornaam"></p>
            </tr>
            <tr>
             <p class="names">Achternaam:</p> <p><input type="text" name="achternaam" id="achternaam"></p>
            </tr>
            <tr>
             <p class="names">Telefoonnummer:</p> <p><input type="text" name="telefoonnummer" id="telefoonnummer"></p>
            </tr>
            <tr>
             <p class="names">Emailadres:</p> <p><input type="text" name="email" id="email"></p>
            </tr>
            <tr>
              <input class="knop" type="submit" name="insert" value="Opsturen" id="insert">
            </tr>
        </form>
    </td>
    </table>
    <br>
    <div id="berichten">

    </div>

    <script>
    var is_valid = true;
    var validator = new FormValidator('form', [{
        name: 'voornaam',
        display: 'Voornaam',    
        rules: 'required'
    }, {
        name: 'achternaam',
        display: 'achternaam', 
        rules: 'required'
    },{
        name: 'telefoonnummer',
        display: 'telefoon', 
        rules: 'required|numeric'
    },{
        name: 'email',
        display: 'email', 
        rules: 'required|valid_email'
    }], function(errors, event) {
        var berichten = document.getElementById('berichten');

        berichten.innerHTML = '';

        if (errors.length > 0) {
            is_valid  = false;
            for (var i = 0, l = errors.length; i < l; i++) {
                berichten.innerHTML += errors[i].message + '<br>';
            }

        }

    });
    </script>
    <script type="text/javascript">
        $(function(){
            $('#insert').click(function(){
                if(is_valid){
                var voornaam = $('#voornaam').val();
                var achternaam = $('#achternaam').val();
                var telefoonnummer = $('#telefoonnummer').val();
                var email = $('#email').val();

                $.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
                    $('#result').html(res);
                });
                document.getElementById('berichten').innerHTML = 'Verstuurd!';   
                }
            });

        });
    </script>

    </div>
    </body>

</html>

action.php

<?php
    //connectie
include ('connection.php');

    //als de knop is ingedrukt insert dan
    if($_POST['action'] == 'button'){

        $voornaam  = mysql_real_escape_string($_POST['voornaam']);
        $achternaam = mysql_real_escape_string($_POST['achternaam']);
        $email  = mysql_real_escape_string($_POST['email']);
        $telefoonnummer = mysql_real_escape_string($_POST['telefoonnummer']);

        $sql = "insert into 
           `form` (`id`,`voornaam`, `achternaam`, `email`, `telefoonnummer`) 
            values ('','".$voornaam."', '".$achternaam."', '".$email."', '".$telefoonnummer."')";
        $query = mysql_query($sql);
        if($query){
            echo "Toegevoegd!";
        }else {
            echo "Er is iets fout gegaan.";
        }
    }
?>

Upvotes: 0

Views: 1155

Answers (5)

Sherin Jose
Sherin Jose

Reputation: 2526

There may be a JQuery conflict in your page, just add one jquery link in your page....Try just like this,

Jquery path:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Form

<form name="myform">
<input type"text" name="name">
<input type="submit" name="submit" id="submitbtn" value="Submit" />
</form>

JS script under body tag

<script>
$('#submitbtn').click(function(){
    //ajax code here
    return false;
})
</script>

The above code is just a sample...workout your code like this...

Upvotes: 0

Priya jain
Priya jain

Reputation: 703

You can also try this : call this function on click like :

<button type="button"  class="btn btn-inverse"   name="submit" onClick="ajaxFormSubmit();">Test</button>

 function ajaxFormSubmit(){
    var voornaam = $('#voornaam').val();
        var achternaam = $('#achternaam').val();
        var telefoonnummer = $('#telefoonnummer').val();
        var email = $('#email').val();
        var atpos=email .indexOf("@");
    var dotpos=email .lastIndexOf(".");

    if(voornaam =="" || achternaam =="" || telefoonnummer =="" ||email ==""){
                  alert("message");       
          return false;
    }
    else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
    {
     alert("msg");
      return false;
    }

    jQuery.post("your data",function(r){
        if(r=="success"){

        }
    });

Upvotes: 0

MSadura
MSadura

Reputation: 1042

With submit button, when for is not valid you need to prevent dfault action by return false

 <script type="text/javascript">
        $(function(){
            $('#insert').click(function(){
                if(is_valid){
                var voornaam = $('#voornaam').val();
                var achternaam = $('#achternaam').val();
                var telefoonnummer = $('#telefoonnummer').val();
                var email = $('#email').val();

                $.post('action.php',{action: "button", voornaam:voornaam, achternaam:achternaam, telefoonnummer:telefoonnummer, email:email},function(res){
                    $('#result').html(res);
                });
                document.getElementById('berichten').innerHTML = 'Verstuurd!';   
                } return false;
            });

        });
    </script>

And by the way for security reason, and for the case when someone have js disabled you should validate data in php also.

Upvotes: 0

Barmar
Barmar

Reputation: 780655

End your click handler function with:

return false;

to prevent the default action of the submit button.

Upvotes: 3

Related Questions