skip to Main Content

The jQuery/JavaScript/Ajax code is not mine. I’m learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don’t understand why or how to fix it.

contact form index.html

 <div class="form">
                    <div id="sendmessage">Your message has been sent. Thank you!</div>
                    <div id="errormessage"></div>
                    <form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
                                <div class="validation"></div>
                            </div>
                            <div class="form-group col-md-6">
                                <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
                                <div class="validation"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
                            <div class="validation"></div>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
                            <div class="validation"></div>
                        </div>
                        <div class="text-center"><button type="submit">Send Message</button></div>
                    </form>
                </div>

contactform.js

jQuery(document).ready(function($) {
  "use strict";

  //Contact
  $('form.contactForm').submit(function() {
    var f = $(this).find('.form-group'),
      ferror = false,
      emailExp = /^[^s()<>@,;:/]+@w[w.-]+.[a-z]{2,}$/i;

    f.children('input').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;

          case 'email':
            if (!emailExp.test(i.val())) {
              ferror = ierror = true;
            }
            break;

          case 'checked':
            if (! i.is(':checked')) {
              ferror = ierror = true;
            }
            break;

          case 'regexp':
            exp = new RegExp(exp);
            if (!exp.test(i.val())) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    f.children('textarea').each(function() { // run all inputs

      var i = $(this); // current input
      var rule = i.attr('data-rule');

      if (rule !== undefined) {
        var ierror = false; // error flag for current input
        var pos = rule.indexOf(':', 0);
        if (pos >= 0) {
          var exp = rule.substr(pos + 1, rule.length);
          rule = rule.substr(0, pos);
        } else {
          rule = rule.substr(pos + 1, rule.length);
        }

        switch (rule) {
          case 'required':
            if (i.val() === '') {
              ferror = ierror = true;
            }
            break;

          case 'minlen':
            if (i.val().length < parseInt(exp)) {
              ferror = ierror = true;
            }
            break;
        }
        i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
      }
    });
    if (ferror) return false;
    else var str = $(this).serialize();
    var action = $(this).attr('action');
    if( ! action ) {
      action = 'contactform/contactform.php';
    }
    $.ajax({
      type: "POST",
      url: action,
      data: str,
      success: function(msg) {
         //alert(msg);
        if (msg == 'OK') {
          $("#sendmessage").addClass("show");
          $("#errormessage").removeClass("show");
          $('.contactForm').find("input, textarea").val("");
        } else {
          $("#sendmessage").removeClass("show");
          $("#errormessage").addClass("show");
          $('#errormessage').html(msg);
        }

      }
    });
    return false;
  });

});


contactform.php

<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');

//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;

//Add new message
if (isset($_POST['name'])){ 


        //Get values
        $contactFormName = $_POST['name'];
        $contactFormEmail = $_POST['email'];
        $contactFormSubject = $_POST['subject'];
        $contactFormMessage = $_POST['message'];


        // 1. check name form field
        if($checkStep == 1){
            if($contactFormName === $_POST['name']){
                $contactFormName = filterName($contactFormName);
                $checkStep++;

            }else{
                echo "No its not working";
            }
        }
            // 2. check email field
            if($checkStep == 2){
                if($contactFormEmail === $_POST['email']){
                    $contactFormEmail = filterEmail($contactFormEmail);
                    $checkStep++;
                }else{
                        echo "Uh Oh! Something went wrong with your email please try again!";
                    }
                }

            // 3. check subject
            if($checkStep == 3){
                if($contactFormSubject === $_POST['subject']){
                    $contactFormSubject = filterSubject($contactFormSubject);
                    $checkStep++;
                }else{
                    echo "Uh Oh! Whats up with your subject";
                }
            }
            // 4. check message
            if($checkStep == 4){
                 if($contactFormMessage === $_POST['message']){
                    $contactFormMessage = filterMessage($contactFormMessage);
                     $checkStep++;
                }else{
                    echo "Uh ho!  Please write us a message";
                }
            }
            // 5. insert message
            if($checkStep == 5){
                $sqlAddMessage = "
                    INSERT INTO contact_form(
                        name,
                        email,
                        subject,
                        message
                    ) VALUES(
                        '$contactFormName', 
                        '$contactFormEmail', 
                        '$contactFormSubject', 
                        '$contactFormMessage'
                    )
                ";
                $queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);

                if($queryAddMessage){

                //code goes here
                }


            }else{
                echo "Uh Oh! NO No No. Check step 5";
            }
        }


?>



3

Answers


  1. The issue is that you’re not setting $msg = “OK” anywhere in your function so the AJAX response is always going to the else statement.

    contactform.php (in // 5. section)

    if($queryAddMessage){
        echo "OK";
    }
    
    Login or Signup to reply.
  2. You should echo msg checked by js in php as OK

    if($queryAddMessage){
    
                    //code goes here
                    echo 'OK';
     }
    
    Login or Signup to reply.
  3. Just use a jQuery form validation plugin to validate form and its easier than using AJAX for the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search