Skip to content
Advertisement

Why is my AJAX method sending form input to the URL?

Once a user submits their form, I want to use JQuery/AJAX to stop the page from redirecting/reloading.

But what is happening, is the user data is refreshed and displayed in the URL – even though I am using the POST method!

I have 2 forms on my landing.html page, but I’ll just give the coding for 1 of them:

It seems my problem is here somewhere in my contactForm.js:

        $(function() {

      $("#contactUsForm input,#contactUsForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
          // additional error messages or events
        },
        submitSuccess: function($form, event) {
          event.preventDefault(); // prevent default submit behaviour
          // get values from FORM
          var name = $("input#c_fName").val();
          var email = $("input#c_email").val();
          var phone = $("input#c_phone").val();
          var message = $("textarea#c_message").val();
          var firstName = name; // For Success/Failure Message
          // Check for white space in name for Success/Fail message
          if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
          }
          
          $.ajax({
            url: "././forms/contactUsForm.php",
            type: "POST",
            data: {
              name: name,
              phone: phone,
              email: email,
              message: message
            },
            cache: false,
            success: function() {
              // Success message
              $('#c_success').html("<div class='alert alert-success'>");
              $('#c_success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
              $('#c_success > .alert-success')
                .append("<strong>Your message has been sent. </strong>");
              $('#c_success > .alert-success')
                .append('</div>');
              //clear all fields
              $('#contactUsForm').trigger("reset");
            },
            error: function() {
              // Fail message
              $('#c_success').html("<div class='alert alert-danger'>");
              $('#c_success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
              $('#c_success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
              $('#c_success > .alert-danger').append('</div>');
              //clear all fields
              $('#contactUsForm').trigger("reset");
            },
            complete: function() {
              setTimeout(function() {
                $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
              }, 1000);
            }
          });
        },
        filter: function() {
          return $(this).is(":visible");
        },
      });

      $("a[data-toggle="tab"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
      });
    });

    /*When clicking on Full hide fail/success boxes */
    $('#c_fName').focus(function() {
      $('#c_success').html('');
    });

landing.html : contactUsForm:

<form name="contactUsForm" id="contactUsForm" action="forms/contactUsForm.php" method="POST">
           
          <!--    First Name      -->
          <div class="control-group form-group col-12" >
            <div class="controls">
              <label for="c_fName">Full Name:</label>
              <input 
              type="text" 
              class="form-control" 
              id="c_fName" 
              name="c_fName" 
              required 
              data-validation-required-message="Please enter your full name.."
              placeholder="Johnny Smith">
            </div>
            
          </div>
          
          <!--   Phone Number      -->
          <div class="control-group form-group">
            <div class="controls">
              <label for="c_phone">Phone Number:</label>
              <input 
              type="tel" 
              class="form-control" 
              id="c_phone" 
              name="c_phone" 
              data-validation-required-message="Please enter your phone number." 
              placeholder="Example: 021 XXX XXXX...">
            </div>
          </div>
          
          <!--    Email Address      -->
          <div class="control-group form-group">
            <div class="controls">
              <label for="c_email">Email Address:</label>
              <input 
              type="email" 
              class="form-control" 
              id="c_email" 
              name="c_email" 
              required 
              data-validation-required-message="Please enter your email address." 
              placeholder="Example: jane.doe@email.com">
            </div>
          </div>
          
          <!--    Message      -->
          <div class="control-group form-group">
            <div class="controls">
              <label for="c_message">Message:</label>
              <textarea 
              rows="6" 
              cols="100" 
              class="form-control" 
              id="c_message" 
              name="c_message" 
              required 
              data-validation-required-message="Please enter your message" 
              maxlength="999" s
              tyle="resize:none" 
              placeholder="Please tell us about your enquiry...">
              </textarea>
            </div>
          </div>
          <div id="c_success"></div>
          
          
          <button 
          type="submit" 
          class="btn btn-primary" 
          id="sendMessageButton" 
          style="width: 100%;margin: auto" >
          Send Message</button>
          
          
        </form>

My contactUsForm.php is working correctly if I do not use AJAX:

        <?php 
    $name = strip_tags(htmlspecialchars($_POST['c_fName']));
    $email_address = strip_tags(htmlspecialchars($_POST['c_email']));
    $phone = strip_tags(htmlspecialchars($_POST['c_phone']));
    $message = strip_tags(htmlspecialchars($_POST['c_message']));
       
    // Create the email and send the message
    $to = 'email@email.com'; 
    $email_subject = "Website Contact Form:  $name";
    $email_body = "You have received a new message from your website contact form.nn"."Here are the details:nnName: $namennEmail: $email_addressnnPhone: $phonennMessage:n$message";
    $headers = "From: email@email.comn"; 
    $headers .= "Reply-To: $email_address";   
    mail($to,$email_subject,$email_body,$headers);
    return true;         
    ?>

If I do not use the AJAX function, the form is submitted, the email sent off and page redirected (Which i do not want)

I have written these forms over and over to try fix this. And every other form I’ve made works perfect with AJAX. These files are located at the end the file:

<script src="assets/vendor/jquery/jquery.min.js"></script> 
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> 
<script src="assets/js/main.js"></script>         
<script src="js/jqBootstrapValidation.min.js" ></script><!--Used for other form-->
<script src="js/bookingForm.js"></script>
<script src="js/contactForm.js"></script>

Advertisement

Answer

Special thanks to @Matt & @El_Vanja for helping with this. I know its not correct for me to post the answer myself. But thought it will help any future devs experiencing the same problem.

After @El_Vanja’s suggestion

I added console.log to each function running to find the problem. The code was running and the email was being sent, but the form data was not binding to the email. This was because the incorrect variable names were used.

After @Matt’s suggestion

The code was running, the email was being sent with the form data, but I was still getting $this is undefined in my console.log on the $.ajax complete function. I then followed @Matt’s suggestion and change $this to $(this). After updating the code, its working:

CONSOLE LOG

submitSuccess has started          contactUsForm.js:11:13
variables have been assigned       contactUsForm.js:20:14
Variable assignment complete       contactUsForm.js:24:14
AJAX Success is starting           contactUsForm.js:36:14

UPDATED contactUsForm.js

        $(function() {

      $("#contactUsForm input,#contactUsForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
          // additional error messages or events
          console.log('Error occured between line 5 - 8');
        },
        submitSuccess: function($form, event) {
            
            console.log('submitSuccess has started');
          event.preventDefault(); // prevent default submit behaviour
          // get values from FORM
          var c_fName = $("input#c_fName").val();
          var c_email = $("input#c_email").val();
          var c_phone = $("input#c_phone").val();
          var c_message = $("textarea#c_message").val();
          var firstName = name; // For Success/Failure Message
          // Check for white space in name for Success/Fail message
          console.log('variables have been assigned');
          if (firstName.indexOf(' ') >= 0) {
            firstName = c_fName.split(' ').slice(0, -1).join(' ');
          }
          console.log('Variable assignment complete');
          $.ajax({
            url: "././forms/contactUsForm.php",
            type: "POST",
            data: {
              c_fName: c_fName,
              c_phone: c_phone,
              c_email: c_email,
              c_message: c_message
            },
            cache: false,
            success: function() {
                console.log('AJAX Success is starting');
              // Success message
              $('#c_success').html("<div class='alert alert-success'>");
              $('#c_success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
              $('#c_success > .alert-success')
                .append("<strong>Your message has been sent. </strong>");
              $('#c_success > .alert-success')
                .append('</div>');
              //clear all fields
              $('#contactUsForm').trigger("reset");
            },
            error: function() {
              // Fail message
              console.log('AJAX error is occuring');
              $('#c_success').html("<div class='alert alert-danger'>");
              $('#c_success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
              $('#c_success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
              $('#c_success > .alert-danger').append('</div>');
              //clear all fields
              $('#contactUsForm').trigger("reset");
            },
            complete: function() {
              setTimeout(function() {
                $(this).prop("disabled", false); // Re-enable submit button when AJAX call is complete
              }, 1000);
            }
          });
        },
        filter: function() {
          return $(this).is(":visible");
        },
      });

      $("a[data-toggle="tab"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
      });
    });

    /*When clicking on Full hide fail/success boxes */
    $('#c_fName').focus(function() {
      $('#c_success').html('');
    });

No change was needed in the contactUsForm.php file

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement