Registration POST using Ajax and get result

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

Sarkis GabrielAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David S.Consultant & Challenge SubduerCommented:
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.
Julian HansenCommented:
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

Sarkis GabrielAuthor 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
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Sarkis GabrielAuthor Commented:
Julian Solution was correct, had to modify this line of code

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

           To -->  var data = $( "form" ).serialize();
Thanks again Julian

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
@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.
Sarkis GabrielAuthor Commented:
You have a point there as yours was 99% complete.

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

Thanks once more .
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.