0

I am trying to submit a form using jquery and ajax.Basically, the issues are:

1.POST request not being sent

2.Form data not being validated

3.The form is not taking data on the second click of the submit button

For the first problem, a POST Request is being sent once I remove the validation portion. However, I do not know why the code mentioned below should not work.

I have no idea why the second problem exists. I have changed the structure of my code time and again, but data is not being validated. I have tested the functions separately and they work, however they do not work when the submit button is pressed, i.e. the if condition that is supposed to send the post data returns false (goes to else), even when the tests inside the if condition are true individually.

The third problem, I suspect, is probably due to the first. I am not so sure though.

scripts pre included are jquery.min.js 1.11.1, twitter bootstraps.min.js

 <!DOCTYPE HTML>
    <html>
    <head>
    <title>Live info a Sports Category Flat Bootstrap Responsive Website Template | Home :: w3layouts</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta property="og:title" content="Vide" />
    <meta name="keywords" content="Live info Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template, 
    Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />

    </head> 


    <?php 

        session_start();
        include 'db.php'; 
        if(isloggedin() == 0) {
            include 'header.php';

         ?>

                <br><br>
    <form id="formdata">        
    <div class="contact signup-body">
                    <div class="login-body">
                        <div class="login-heading">
                            <h3>Sign up</h3>
                        </div>
                        <div class="login-info">
                                <input type="text" class="user" id="name" name="name" placeholder="Name" >
                            <div id="namem" style='text-align:center;color:red;'></div>

                                <input type="text" class="user" id="email" name="email" placeholder="Email">
                            <div id="emailm" style='text-align:center;color:red;'></div>

                                <input type="text" class="user" id="mobile" name="mobile" placeholder="Phone">
                            <div id="mobilem" style='text-align:center;color:red;'></div>

                                <input type="password" id="password" name="password" class="lock" placeholder="Password">
                            <div id ="passm" style='text-align:center;color:red;'></div>

                            <input type="password" id="repassword" name="repassword" class="lock" placeholder="Confirm Password"                            >
                                <div id = "repassm" style='text-align:center;color:red;'></div>

                                <input type="submit" id="signin" name="signin" value="Sign up">
                                <div class="signup-text">
                                    <a href="#"  data-toggle="modal" data-target="#myModal">Already have an account? Login here.</a>
                                </div>
                        </div>
                    </div>

                    <!-- Modal -->

                    <!-- // Modal -->
                </div>
    </form>
                <!-- //contact -->
            </div>


     <script src="js/jquery-1.11.1.min.js"></script>
    <script>
      $(document).ready(function(){ 

          $('#signin').click(function(event){
           event.preventDefault();
           var name = $('#name').val();
         var email = $('#email').val();
         var mobile = $('#mobile').val();
         var password = $('#password').val();
         var repassword = $('#repassword').val();

        var email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        var mob_fil = /^[0-9]{10}$/i;
        var string = /^[ a-zA-Z]+$/;
        var pass = /^[a-zA-Z0-9_\.\-\@\!]*$/;


              if (!(name == '' || email == '' || mobile== '' || password == '' || repassword == '')){

              if (!email_filter.test(email)) {$('#emailm').html('Please provide a valid email address');}

        if (!mob_fil.test(mobile)) {$('#mobilem').html('Please enter a 10 digit number');}

        if (!string.test(name))  {$('#namem').html('Please enter only alphabets');}

        if (!pass.test(password)) {$('#passm').html('Only alphabets,digits and special characters allowed in password');}

        if(password.length<3) {$('#passm').html('please enter a bigger password');}

        if (password!=repassword) {$('#repassm').html('Password and Confirm password do not match');}
               }

            if((email_filter.test(email)==true) && (mob_fil.test(mobile)==true) && (string.test(name)==true) && pass.test(password) && (password.length>3) && (password=repassword))
                                {
                        var dataString = $('#formdata').serializeArray();

                                $.ajax({
                                        type: "POST",
                                        url: "register.php",
                                        data: dataString,
                                        dataType:"text",
                                        contentType: 'application/x-www-form-urlencoded',
                                        cache: false,
                                        success: function(result){
                                        var data="";
                                        $("#message").html('success');
                                        $("#name").val('');
                                        $("#email").val('');
                                        $("#mobile").val('');
                                        $("#password").val('');
                                        $("#repassword").val('');
                                        },
                                        error: function(error){console.log(error);}
                                });   
                            }
              else {$('#repassm').html("your form is not valid");}

          });

      });
    </script>

        <?php include 'login_modal.php';session_destroy();}
              else {  $url = 'index.php'; echo '<META HTTP-EQUIV=REFRESH CONTENT="0; '.$url.'">';} ?>



          <!-- main content end-->
    </div>
    </div>
    </div>
    <?php include 'footer.php' ?>
    </section>
    </body>
    </html>

I posted a question previously and found out that the validation part is buggy.

Also, the console shows no jQuery errors.

4
  • Have you considered using jQuery validate and putting the submission into the submitHandler? jqueryvalidation.org/validate Commented Jul 7, 2016 at 15:33
  • You probably want session_start() before anything is output to the screen (above <!DOCTYPE ... - otherwise it'll not be able to set the session cookie. Commented Jul 7, 2016 at 15:35
  • No. To be honest i am a beginner and prefer to use functions i can understand, instead of libraries. But i am open to alternatives. Anything that can solve this will be huge for me.@Rasclatt Commented Jul 7, 2016 at 15:35
  • As far as i am concerned, i want my form data to be taken in, validated and submitted in one session, and the session then being destroyed. I shall move the session_start() bit at the top, but i don't think that that portion causes a bug @CD001 Commented Jul 7, 2016 at 15:38

2 Answers 2

2

First thing I'd suggest is don't do your validation in JQuery. Send the data to PHP and do the checking there.

Second, you've got a spelling error here: event.prevetnDefault();

Third, you're not doing anything with the results returned from register.php

success: function(result){
  var data="";
  $("#message").html('success');
  $("#name").val('');
  $("#email").val('');
  $("#mobile").val('');
  $("#password").val('');
  $("#repassword").val('');
  console.log(result); // Check the result in console
},

Fourth, you mentioned it working when you removed the validation. Remove the validation one step at a time until you figure out which one is causing the problem. But like I said, you should be doing your validation in PHP.

Edit: I could be wrong, but I think maybe this line needs to be re-written:

if (!(name == '' || email == '' || mobile== '' || password == '' || repassword == '')){

if (name != '' && email != '' && mobile != '' && password != '' && repassword != '') {
Sign up to request clarification or add additional context in comments.

2 Comments

Agreed. Client-side validation is very nice for user-friendliness, but it doesn't protect the server-side from invalid data, because it can always be bypassed or modified by a malicious user. If you value the integrity of your database, do server-side validation first. Once that's working, worry about client-side. And I would use the jQuery validate plugin too, as another commenter suggsted. It's very easy and will probably save you a lot of time
@awl19 thankyou! my form is working right now due to your edit. Also, it turned out that i had edited bootstrap.min.js for a custom division. However i still can not get data on the second click of the submit button. I am marking your answer as accepted and posting it as a different question
-1

You can use a normal button instead of submit button, then add return false like this:

if(mobile != ''){
    if (!mob_fil.test(mobile)){
    $('#mobilem').text('Please enter a 10 digit number');
    return false;
    } 
}

2 Comments

could you explain how? is that portion to be added into the html? or is it fine if it's inside the submit function?
that's not the issue. default submission of the form is already prevented by event.preventDefault(); The issue seems to be that the validation code doesn't work as intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.