Ajax form submit returns 404 error on submit

658 Views Asked by At

I used Mobirise to create a bootstrap based website with a contact form towards the end of it. The form originally had an action just taking it to the Mobirise website. I have previously used ajax and PHP to create mailer forms, and so modified files I had on hand to handle this form. However, whenever I click on the submit button, I get the following error in the console:

POST http://www.mywebsite.com/captcha-lib.php 404 (Not Found)

I have checked and verified that php is enabled on the server (Bluehost), and that the file in question is along the correct path, and that it is on the remote server (it is). Can anyone help me determine why I am getting this error? I have provided the HTML, Ajax, and PHP for all relevant elements below, with private keys and data removed.

Below is the html for the form itself:

<form data-form-title="Let's Work Together">
      <input type="hidden" value="3S/6rrqxqgfL9WCp8yG49uE1861hrI6n4k9XNv8Q5Awspyeq+y1eU1g/jgUsPbIH+KZRWaBHkHuhzqxyJ39m7DSH7QZBYD6IZFqS6415lGnscjkO2Frp6/UUrh4xDIED" data-form-email="true">
      <div class="col-xs-12 col-md-8 col-md-offset-2 form-wrap">
           <div class="col-xs-12">
                <div class="form-group">
                     <label class="form-control-label">Name*</label>
                     <input type="text" class="form-control" id="name" name="name" required="" data-form-field="Name" placeholder="Name*">
                </div>
           </div>
           <div class="col-xs-12">
                <div class="form-group">
                     <label class="form-control-label">Email*</label>
                     <input type="email" class="form-control" id="email" name="email" required="" data-form-field="Email" placeholder="Email*">
                </div>
           </div>
           <div class="col-xs-12">
                <label class="form-control-label">Please leave a detailed message and include the type of project you have, as well as how extensive it is.</label>
                <textarea class="form-control" id="message" name="message" rows="7" data-form-field="Message" placeholder="Please leave a detailed message and include the type of project you have, as well as how extensive it is."></textarea>
            </div>
            <div style="float: left;" class="g-recaptcha" data-sitekey="6LetWgITAAAAANNDaTINxoYz9xyOkp2rchwrQMbX"></div>
      </div>
      <div class="clear"></div>
      <div class="form-separator"></div>
      <div class="col-xs-12 col-md-8 col-md-offset-2 form-button-wrap">
           <div class="text-xs-center text-md-right"><button type="submit" class="btn btn-lg btn-primary"><span class="fa fa-send mbr-iconfont mbr-iconfont-btn" style="color: rgb(255, 255, 255);"></span>Email Me</button></div>
      </div>
 </form>

I am handling the form using ajax, and I added captcha to decrease the chance of spam emails. The javascript/ajax, which is at the end of the html document is as follows:

<script type="text/javascript">
     function validateEmail(email) {
         var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
      return regex.test(email);
      }
      $('form').submit(function(e) {
           var getErrors = [];
           e.preventDefault();
           $(this).find('input').each(function(){
                if($(this).val() == "" && $(this).is(':visible')) {
                     $(this).addClass('is-required');
                     getErrors.push($(this).attr('id'));
                } else {
                     $(this).removeClass('is-required');
                }
                if($(this).attr('id') == "email") {
                     var testEmail = $(this).val();
                     if(validateEmail(testEmail)){
                           $(this).removeClass('is-required');
                      } else {
                           $(this).addClass('is-required');
                           getErrors.push($(this).attr('id'));
                      }
                 }
            })
            $(this).find('textarea').each(function(){
                 if($(this).val() == "") {
                      $(this).addClass('is-required');
                      getErrors.push($(this).attr('id'));
                      if($(this).hasClass('g-recaptcha-response')) {
                           $('.g-recaptcha').addClass('is-required')
                      }
                 } else {
                      $(this).removeClass('is-required');
                      if($(this).hasClass('g-recaptcha-response')) {
                           $('.g-recaptcha').removeClass('is-required')
                      }
                 }
            })
            if(getErrors.length < 1) { 
                 $('.form-container form, .form-container .title').hide();
                 $('.form-container .sending').show();
                 var name = $('#name').val();
                 var email = $('#email').val();
                 var message = $('#message').val();
                 var captcha = $('#g-recaptcha-response').val();
                 $.ajax({
                      type: "POST",
                      url: "captcha-lib.php", 
                      data:{ 
                         "name": name,
                         "email": email,
                         "message": message,
                         "g-recaptcha-response": captcha
                      }
                  }).done(function(data){     
                       $('.form-container .success').show();  
                       $('.form-container .sending').hide();
                  }).fail(function(data){
                       $('.form-container .failed').show();  
                       $('.form-container .sending').hide();
                  });
            }
            return false;
        })
</script>

The captcha-lib.php file was originally in a folder along the path assets/php, where the assets folder was in the website root folder. I have since moved captcha-lib.php into the root folder, so that it is in the same location as the index.html file containing the ajax. Here is the code in captcha-lib.php:

<?php
header("Access-Control-Allow-Origin: https://www.google.com");

class ReCaptchaResponse
{
    public $success;
    public $errorCodes;
}

class ReCaptcha
{
    private static $_signupUrl = "https://www.google.com/recaptcha/admin";
    private static $_siteVerifyUrl =
        "https://www.google.com/recaptcha/api/siteverify?";
    private $_secret;
    private static $_version = "php_2.0";

    function ReCaptcha($secret)
    {
        if ($secret == null || $secret == "") {
            die("To use reCAPTCHA you must get an API key from <a href='"
                . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
        }
        $this->_secret=$secret;
    }
    private function _encodeQS($data)
    {
        $req = "";
        foreach ($data as $key => $value) {
            $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
        }
        // Cut the last '&'
        $req=substr($req, 0, strlen($req)-1);
        return $req;
    }

    private function _submitHTTPGet($path, $data)
    {
        $req = $this->_encodeQS($data);
        $response = file_get_contents($path . $req);
        return $response;
    }

    public function verifyResponse($remoteIp, $response)
    {
        // Discard empty solution submissions
        if ($response == null || strlen($response) == 0) {
            $recaptchaResponse = new ReCaptchaResponse();
            $recaptchaResponse->success = false;
            $recaptchaResponse->errorCodes = 'missing-input';
            return $recaptchaResponse;
        }
        $getResponse = $this->_submitHttpGet(
            self::$_siteVerifyUrl,
            array (
                'secret' => $this->_secret,
                'remoteip' => $remoteIp,
                'v' => self::$_version,
                'response' => $response
            )
        );
        $answers = json_decode($getResponse, true);
        $recaptchaResponse = new ReCaptchaResponse();
        if (trim($answers ['success']) == true) {
            $recaptchaResponse->success = true;
        } else {
            $recaptchaResponse->success = false;
            $recaptchaResponse->errorCodes = $answers [error-codes];
        }
        return $recaptchaResponse;
    }
}

// your secret key
$secret = MY SECRET CAPTCHA KEY;

// empty response
$response = null;

// check secret key
$reCaptcha = new ReCaptcha($secret);

// if submitted check response
if ($_POST["g-recaptcha-response"]) {
    $response = $reCaptcha->verifyResponse(
        $_SERVER["REMOTE_ADDR"],
        $_POST["g-recaptcha-response"]
    );
}

if ($response != null && $response->success) {
    // TODO change to [email protected]
    $email_to = "MYEMAILADDRESS"; // TODO - update when site is live
    $noreply = "Me<MYEMAILADDRESS>"; // TODO - update when site is live
    $autogreet = "Thank you for contacting me regarding my services! I will respond to your email as soon as I can. Please be patient in the meantime!\n";
    $email_subject = "Me, Web Designer'";
    $name = $_POST['name']; // required 
    $email = $_POST['email']; // required
    $message = $_POST['message']; // required
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
    $email_message .= "".clean_string($message)."\n";
    $email_message .= "".clean_string($name)."\n";

    $email = $name.'<'.$email.'>'; 
    // create email headers
    $headers = 'From: '.$email."\r\n".
    'Reply-To: '.$email."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);  
} else {
    header("HTTP/1.0 404 Not Found");
    // TODO find a way to email an issue @mail("MYEMAILADDRESS", "There is an issue with php emailer", "The php resolved a 404. Please contact your web developer to resolve the issue.", "[email protected]"); 
}

?>
0

There are 0 best solutions below