2

I am trying to submit a form using jquery and ajax. I have been at this for the past 2 DAYS but i do not know why this isn't working. Basically, the issues are:

  1. Get request sent instead of post
  2. Form data not being validated
  3. the form is reset after i press submit button.

for the 1st problem, I have tried using $.post() as well, but that doesn't work either. I tried using dataType:'text', which didn't work either. Also, as @AnilPanwar pointed out, i used #formdata instead of this , which didn't work either

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 3rd 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

Please, please help me out.

<!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.prevetnDefault();
       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>

also, using console there are no js errors shown. A GET request is sent from the page when submit is clicked, with the field values in the URL.

Below are the links to snaps i took of the form

a snapshot of the console after submitting the form: a snapshot of the console after submitting the form

a snapshot of the requests after submitting the form: a snapshot of the requests after submitting the form

As @ADyson pointed out, the data inputted into the form is not being stored. I moved the variable declarations inside the submit function to solve that. That does solve problem number 3. But now, i cannot get data into my script when i press the submit button for a second time. I have put the edited code into the question.

5
  • 1
    Instead $(this).serializeArray(); use $("#formdata").serializeArray(); Commented Jul 7, 2016 at 12:54
  • @AnilPanwar is right, in your case $(this) => button , not the form! Commented Jul 7, 2016 at 13:03
  • i tried that out! it still isn't working :( Commented Jul 7, 2016 at 13:19
  • Please don't change your question after getting an answer. Instead, rollback your edit to this question and add a new question which fully explains the new situation. Commented Jul 7, 2016 at 15:32
  • Alright! i have posted a new question at: stackoverflow.com/questions/38249526/… Commented Jul 7, 2016 at 15:34

1 Answer 1

2

Your form is submitting (in the conventional way with a full refresh) before the ajax call can be made. That's why you're seeing a GET request. This happens because your button is input[type="submit"]. The default behaviour of this type of button is to submit the form it is within when clicked.

The solution:

First, move event.preventDefault(); right to the first line of your click event. This will stop the form submission from happening. Currently the prevention is happening too late in the process (and not at all when the form is invalid).

Second, as mentioned in the comments, replace $("#this").serializeArray(); with $("#formdata").serializeArray();. In the context of the click event, $(this) means the button that was clicked, not the whole form.

Third, move

       var name = $('#name').val();
 var email = $('#email').val();
 var mobile = $('#mobile').val();
 var password = $('#password').val();
 var repassword = $('#repassword').val();

inside your click event. Otherwise the validation will probably fail, because currently these variables are being populated when the page loads, not when the user submits. If you then use these variables to check the validity of the data at submission, they don't take into account what the user has entered into the fields.

Lastly, remove event.unbind(); entirely. Unbind applies to elements, not to events. I don't think this command is actually doing anything bad necessarily, but it's better to remove redundant/incorrect code. See http://api.jquery.com/unbind/ for how to use this method.

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

8 Comments

i put event.preventDefault() as the first line of the submit function. Now my form is not being submitted, there is no get or post request is sent. and yes, i removed event.unbind() as well. I suppose there is something wrong with the all those if conditions.
well, your answer solved problem number 3! thankyou so very much :) :D sadly i don't have enough reputation to upvote you :(
do you get any errors in the browser console? Does all your validation criteria definitely work? Try temporarily removing all the validation code and just leaving the ajax call in, and see if it works. Then put the validation code back a bit at a time until it stops working again.
I've just noticed that you're collecting the values of the fields, which you are using to do the validation, when the page loads, not waiting till the user submits the form. So they are probably empty. That's almost certainly why nothing is happening. I'll edit the answer with extra advice
yes, exactly. i just put the var declarations inside the submit function. that sorted a few things out. Thankyou. Also, i have posted links to snaps of the console. I am currently editing out the validation part of the form and shall get back once it's done
|

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.