Thursday, July 17, 2014

Submit a form without refreshing page using ajax and PHP

This is very simple function.Ajax is used to submit a form without refreshing page.




Live DemoDownload Script


Step 1:
    Need library function.Just copy and paste the below library file.
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

jQuery Code

<script type="text/javascript" >
    $(function() {
        $(".submit").click(function() {
        var name = $("#name").val();
        var email = $("#email").val();
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      
        var dataString = 'name='+ name + '&email=' + email;
       
        if(name=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a name</div>');;
            $("#name").focus();
        }
        else if(email=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a email address</div>');;
            $("#email").focus();
        }
        else if(reg.test(email) == false)
          {
                $('.success').fadeOut(200).hide();
                $('.error').fadeOut(200).show().html('<div class="notice" align="left">Please enter a valid email address</div>');;
                $("#email").focus();
          }
        else
        {
            $.ajax({
                type: "POST",
                url: "mail.php",
                data: dataString,
                success: function(){
                $('.success').fadeIn(200).show();
                $('.error').fadeOut(200).hide();
            }
            });
        }
        return false;
        });
    });
    </script>

HTML form

<form method="post" name="form">
  <p>Name:
    <input id="name" name="name" type="text" />
  </p>
  <p>Email:
    <input id="email" name="email" type="email" required />
  </p>
  <span class="error" style="display:none; color:#FF0000"> Please enter valid data</span> <span class="success" style="display:none;color:#33CC66"> Thank You.Your mail has been sent successfully.</span>
  <p>
    <input type="submit" name="submit" value="Submit" class="submit"/>
  </p>
</form>

Please share your comments and feedback.Thanks.Please subscribe my updates via email.

No comments:

Post a Comment