Argiris
Argiris

Reputation: 189

Ajax and JQuery to post a form without refreshing

Well i am trying to create a form that will not refresh the page after submit. After reading few papers on how to do that i came up with this code:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){

        // enter key
        $("input").keypress(function(event) {
            if (event.which == 13) {
                doLogin();
            }
        });
    });

    function doLogin() {

        if(!checkLoginField())
            return;
        $("#myform").validate({
            debug: false,
            submitHandler: function(form) {
                // do other stuff for a valid form
                $.post('process.php', $("#myform").serialize(), function(data) {
                    $('#results').html(data);
                });
            }
        });
        return;
    }

    function checkLoginField() {

        $("#errEmptyEmail").css("display","none");
        $("#errEmptyName").css("display","none");

        if($("#email").val() == '') {
            $("#errEmptyEmail").css("display","block");
            return false;   
        }

        if($("#name").val() == '') {
            $("#errEmptyName").css("display","block");
            return false;
        }

        return true;
    }
</script>

And here is the form:

<form name="myform" id="myform" action="" method="POST">  
    <label>Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/>  
    <br><br>
    <label>Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
    <br><br>
    <input type="submit" name="submit" value="Submit" onClick="doLogin();"> 
</form>
<div class="wrapError" id="errEmptyEmail">Please enter your email address.</div>
<div class="wrapError" id="errEmptyName">Please enter your name.</div>
<div id="results"><div>

On process.php there is code that handles the name/email (and other variables that will be added later). But the problem that i have right now is that when my form is empty and i press submit i get the error but after a while it disappears, because as i noticed the page is being refreshed.

Any suggestions?

Also is this style vulnerable for injections? cause i am planing to make an account manager so, i was also wondering if this is safe approach to handle data.

Upvotes: 1

Views: 285

Answers (3)

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13699

I believe setting submitHandler will prevent the form from submitting. But in your case, you set the validation config inside doLogin() function which the default form submission was triggered before it went to the validation.

Put the validation config outside the doLogin() and set rules instead.

Have it this way :

$(document).ready(function() {
  // add rules so it won't submit if it didn't satisfy what you set
  $("#myform").validate({
    debug: false,
    rules: {
      "email": {
        required: true,
        email: true
      },
      "name": {
        required: true
      }
    },
    submitHandler: function(form) {
      // do other stuff for a valid form
      $.post('process.php', $("#myform").serialize(), function(data) {
        $('#results').html(data);
      });

      return false; // if default form submission was not blocked, add this.
    }
  });

  $("#myform").submit(function(e) {
    checkLoginField(); // this will just hide or show elements
  });
});


function checkLoginField() {
  $("#errEmptyEmail").css("display", "none");
  $("#errEmptyName").css("display", "none");

  if ($("#email").val() == '') {
    $("#errEmptyEmail").css("display", "block");
  }

  if ($("#name").val() == '') {
    $("#errEmptyName").css("display", "block");
  }
}

Upvotes: 1

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Prevent default action of form while you submit

$("#myform").submit(function(e) {
    e.preventDefault(); //this prevents form from getting submitted
}).validate({
        debug: false,
        submitHandler: function(form) {
            // do other stuff for a valid form
            $.post('process.php', $("#myform").serialize(), function(data) {
                $('#results').html(data);
        });
     }
});

Regarding your second question, since I do not have much knowledge on php, I will not be adding my answer, but then its all server side process you do with data, which actually eliminates vulnerability. so I would say you might need to look on how you handle received data in your server side securely. There are various aspects on this, and you will get many if you google.


UPDATE

DEMO

Also, you do not need to handle click event with an onclick method because by default submit button's functionality is to submit the form and you also don't need error fields separately, because jquery validate does it for you. And you just need to add required attribute to your inputs. So I would like to modify your code as below:

<form name="myform" id="myform" action="" method="POST" novalidate>  
    <label>Name</label>  
    <input type="text" required name="name" id="name" size="30" value=""/>  
    <!--Just add the required attribute-->
    <br><br>
    <label>Email</label>  
    <input type="text" required name="email" id="email" size="30" value=""/> 
    <!--Just add the required attribute-->
    <br><br>
    <input type="submit" name="submit" value="Submit"> 
</form>
<div id="results"><div>

And JS you can add extra option in .validate, to specify what should be error color and you can make use of option errorClass as below:

$("#myform").submit(function(e) {
    e.preventDefault(); //this prevents form from getting submitted
}).validate({
    debug: false,
    errorClass:'invalid', //Add this for error class
    submitHandler: function(form) {
        alert('Success');
        return false;
        // do other stuff for a valid form
        $.post('process.php', $("#myform").serialize(), function(data) {
            $('#results').html(data);
        });
    }
});

Your errorClass CSS be like:

.invalid{
    color:red;
}

Upvotes: 1

Francesco
Francesco

Reputation: 441

On the onClick add event argument and preventDefault when login failed.

function doLogin(event) {

        if(!checkLoginField()) {
            event.preventDefault();
            return;
        }
        $("#myform").validate({
            debug: false,
            submitHandler: function(form) {
                // do other stuff for a valid form
                $.post('process.php', $("#myform").serialize(), function(data) {
                    $('#results').html(data);
                });
            }
        });
        return;
    }

For security question there are two issues: you are sending password without encrypting it and for avoiding man-in-the-middle vulnerability, you should run all app over https.

Upvotes: 0

Related Questions