Registration POST using Ajax and get result

Sarkis Gabriel
Sarkis Gabriel used Ask the Experts™
on
Good Evening Everyone

I am trying to do a registration MODAL to post using php and get back a confirmation result, I have it working in the normal submission method POST using php, which passes the variables and reloads the page to registration.php after submission.

This is the MODAL below :
           <!--Body-->
                    <div class="modal-body">
                        <form method="POST" action="/registration.php">
                      <div class="md-form form-sm mb-5">
                        <i class="fas fa-user prefix" style="color: dodgerblue "></i>
                          <input class="form-control" id="fname" name="fname" type="text" placeholder="&nbsp First Name"><br>
                      </div>

                      <div class="md-form form-sm mb-5">
                        <i class="prefix"></i>
                          <input class="form-control" id="lname" name="lname" type="text"  placeholder="Last Name"><br>
                      </div>

                      <div class="md-form form-sm mb-4">
                        <i class="fas fa-address-book prefix"></i>
                          <input class="form-control" id="address" name="address" type="text"  placeholder="Address"><br>
                      </div>
                        <div class="container">
                        <div class="form-check-inline">
                            <label class="form-check-label">
                                <input type="radio" id="gender" name="gender" value="M" class="form-check-input" name="optradio" checked="checked">Male
                            </label>
                        </div>
                        <div class="form-check-inline">
                            <label class="form-check-label">
                                <input type="radio" id="gender" name="gender" value="F" class="form-check-input" name="optradio">Female
                            </label>
                        </div>
                        </div>
                        <div class="md-form form-sm mb-4">
                            <i class="far fa-calendar prefix" style="color: dodgerblue "></i>
                            <input class="form-control" id="dob" name="dob" type="date"  placeholder="Date Of Birth"><br>
                        </div>
                        <div class="md-form form-sm mb-4">
                            <i class="fas fa-phone prefix" style="color: dodgerblue "></i>
                            <input class="form-control" id="contact" name="contact" type="text" placeholder="Tel Number"><br>
                        </div>
                        <div class="md-form form-sm mb-4">
                            <i class="fas fa-at prefix"></i>
                            <input class="form-control" id="email" name="email" type="email" placeholder="Email Address"><br>
                        </div>
                        <div class="md-form form-sm mb-4">
                            <i class="fas fa-key prefix"></i>
                            <input class="form-control" id="password" name="password" type="password" placeholder="Password....."><br>
                        </div>
                        <div class="md-form form-sm mb-4">
                            <i class="fas fa-key prefix"></i>
                            <input class="form-control" id="cpassword" name="cpassword" type="password" placeholder="Confirm Password....."><br>
                        </div>
                      <div class="text-center form-sm mt-2">
             <!--          <button type="button" name="sign_up" id="sign_up" class="btn btn-info">Sign up <i class="fas fa-sign-in ml-1"></i></button> -->
                          <button class="btn btn-default">Signup</button>
                      </div>
                        </form>
                    </div>

Open in new window

If I can get assistance in the script would be helpful..

  <script> /*
    $(document).ready(function(){
        $('#sign_up').click(function(){
            var fname = $('#fname').val();
            var lname = $('#lname').val();
            var address = $('#address').val();
            var gender = $("input[name='gender']:checked").val();
            var dob = $('#dob').val();
            var contact = $('#contact').val();
            var email = $('#email').val();
            var password = $('#password').val();
            var cpassword = $('#cpassword').val();
 
            if(fname !== '' && lname !== ''&& address !== ''&& gender !== ''&& dob !== ''
                && email !== ''&& password !== ''&& cpassword !== '')
            {
                $.ajax({
                    url:"registration.php",
                    method:"POST",
                    data: {fname:fname, lname:lname, address:address, gender:gender,
                        dob:dob, contact:contact, password:password, cpassword:cpassword},
                    success:function(data)
                    {
                        console.log(data);

                        //alert(data);
                        if(data === 'No')
                        {
                            alert("Wrong Data");
                        }
                        else
                        {
                            $('#sign_up').hide();
                            location.reload();
                        }
                    }
                });
            }
            else
            {
                alert("All Fields are required");
            }
        });

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David S.Consultant & Challenge Subduer
Top Expert 2009

Commented:
First of all, thank you for making it work without AJAX first. All too few developers do that.

Secondly, where are the <label>s?
http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/
https://www.smashingmagazine.com/2018/06/placeholder-attribute/
https://www.aaron-gustafson.com/notebook/labeled-with-love/
https://websemantics.uk/archived/accessible-forms/
https://jimthatcher.com/webcourse8.htm

Third, doesn't calling location.reload() defeat the point of using AJAX? Perhaps you intended to ask what to replace that with?

P.S. It's better to use the form's submit event than a button's click event.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
First up welcome to EE.
A general comment. Your post is always going to be much easier to read (and respond to) if you use code tags around your code snippets. To do this
a) Highlight your code
b) Click the CODE Button in the toolbar
I have done this for you.

Secondly, to your question. Some general pointers on submitting by AJAX
1. Always use preventDefault() on the event otherwise your form will do a normal submit and result in a double submission and kill the AJAX complete.
2. Learn about jQuery serialize() - it will make collecting your form data much easier.

Having said that here is how you can refactor your code
<script>
$(function(){
  $('#sign_up').click(function(e){

    // PREVENT DEFAULT <form> ACTION
    e.preventDefault();

    // SERIALIZE THE <form> DATA
    var data = $(this).serialize();

    // PUT VALIDATION IN A FUNCTION. HERE WE PASS AN ARRAY OF FIELDS
    // WE WANT TO VALIDATE
    // BECAUSE <form> SUBMIT IS HANDLED ON THE submit CLICK WE PASS this.form
    // GET VALIDATION OUT THE WAY SO YOU DON'T HAVE A LOT OF NESTED if STATEMENTS
    if (!validate(this.form, ['fname','lname','address','gender','dob','email','password','cpassword'])) { 
      alert('Form is not valid, please complete all fields');
      return;
    }

    // NOTE USE OF .then() RATHER THAN success (WHICH HAS BEEN DEPRECATED)
    $.ajax({
      url:"registration.php",
      method:"POST",
      data: data
    })
    .then(function(resp) {
      console.log(data);
      //alert(data);
      if(data === 'No') {
        alert("Wrong Data");
      }
      else {
        $('#sign_up').hide();
        location.reload();
      }
    })
  });

   // SIMPLE VALIDATION FUNCTION
   function validate(form, fields)
   {
     for(var i = 0; i < fields.length; i++) {
       if (!form[fields[i]].value) return false;
     }
     return true;
   }
});
</script>

   function validate
});
</script>

Open in new window

Author

Commented:
Thanks Julian for the assistance..

I have tried the code and I understand it but I just don't know why it is not working.

Only thing I can think of that

if (isset($_POST['fname'])){}
is not activating when it is posting.

The console.log (data); not showing any log for some reason.

If you can think of anything that would be great.

Thanks again
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Julian Solution was correct, had to modify this line of code

           From -->  var data = $(this).serialize();

           To -->  var data = $( "form" ).serialize();
Thanks again Julian
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
@Sarkis, you have acknowledge my solution but made your solution the accepted one - was this intentional?

Let me know and I will open the question again.

Author

Commented:
You have a point there as yours was 99% complete.

Still learning the system, do mind my ignorance :) .

Thanks once more .
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial