0

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.";
        }
    }
?>
1
  • you could make use of jquery form validation if you like, it has also a remote method for validating elements from server. jqueryvalidation.org Commented Jan 13, 2014 at 8:49

5 Answers 5

3

End your click handler function with:

return false;

to prevent the default action of the submit button.

Sign up to request clarification or add additional context in comments.

1 Comment

That will still always submit the form.
0

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.

1 Comment

If I add return false; it will still submit the data, no matter what is put in the form, and It won't show the error messages not even when I change the button back to submit.
0

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"){

        }
    });

Comments

0

http://www.javascriptkit.com/javatutors/valid3.shtml

http://www.nairaland.com/216098/form-validation-tutorial-using-javascript

See if this links help you thy actually helped me...

Comments

0

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...

2 Comments

You just add an alert(1); first inside the click handler function and make sure that is is calling....otherwise sure there is a conflict
Just change your submit button to button...and then click and take console in your browser and findout what script error is occured in your js code...