简体   繁体   中英

Failed to load resource: the server responded with a status of 404 (Not Found) on contact form using Js, ajax, php

I am getting the error Failed to load resource: the server responded with a status of 404 (Not Found) and not really sure why it is happening. I have checked the routes and access of the files and everything seems fine.

My Js file looks like this:

var clContactForm = function() {

        /* local validation */
        $('#contactForm').validate({

            /* submit via ajax */
            submitHandler: function(form) {

                var sLoader = $('.submit-loader');

                $.ajax({

                    type: "POST",
                    url: "../inc/sendEmail.php",
                    data: $(form).serialize(),
                    beforeSend: function() { 

                        sLoader.slideDown("slow");

                    },
                    success: function(msg) {

                        // Message was sent
                        if (msg == 'OK') {
                            sLoader.slideUp("slow"); 
                            $('.message-warning').fadeOut();
                            $('#contactForm').fadeOut();
                            $('.message-success').fadeIn();
                        }
                        // There was an error
                        else {
                            sLoader.slideUp("slow"); 
                            $('.message-warning').html(msg);
                            $('.message-warning').slideDown("slow");
                        }

                    },
                    error: function() {

                        sLoader.slideUp("slow"); 
                        $('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo");
                        $('.message-warning').slideDown("slow");


                    }

                });
            }

        });
    };

My php code looks like this:

<?php

// Replace this with your own email address
$siteOwnersEmail = 'myemail@gmail.com';


if($_POST) {

    $name = trim(stripslashes($_POST['contactName']));
    $email = trim(stripslashes($_POST['contactEmail']));
    $subject = trim(stripslashes($_POST['contactSubject']));
    $contact_message = trim(stripslashes($_POST['contactMessage']));

    // Check Name
    if (strlen($name) < 2) {
        $error['name'] = "Por favor, coloca tu nombre.";
    }
    // Check Email
    if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
        $error['email'] = "Por favor, pon un correo válido.";
    }
    // Check Message
    if (strlen($contact_message) < 15) {
        $error['message'] = "Por favor, coloca tu mensaje";
    }
    // Subject
    if ($subject == '') { $subject = "Contact Form Submission"; }


    // Set Message
    $message .= "Email from: " . $name . "<br />";
    $message .= "Email address: " . $email . "<br />";
    $message .= "Message: <br />";
    $message .= $contact_message;
    $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";

    // Set From: header
    $from =  $name . " <" . $email . ">";

    // Email Headers
    $headers = "From: " . $from . "\r\n";
    $headers .= "Reply-To: ". $email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";


    if (!$error) {

        ini_set("sendmail_from", $siteOwnersEmail); // for windows server
        $mail = mail($siteOwnersEmail, $subject, $message, $headers);

        if ($mail) { echo "OK"; }
        else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; }



    } # end if - no validation error

    else {

        $response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
        $response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
        $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;

        echo $response;

    } # end if - there was a validation error

}

?>

And finally, my HTML code is this one:

<div class="row section-header" data-aos="fade-up">
            <div class="col-full">
                <h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1>
            </div>
        </div>

        <div class="row contact-content" data-aos="fade-up">

            <div class="contact-primary">

                <h3 class="h6">Envíanos un mensaje</h3>

                <form name="contactForm" id="contactForm" method="post" action="/index.html" novalidate="novalidate">
                    <fieldset>

                    <div class="form-field">
                        <input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width">
                    </div>
                    <div class="form-field">
                        <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width">
                    </div>
                    <div class="form-field">
                        <input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width">
                    </div>
                    <div class="form-field">
                        <textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea>
                    </div>
                    <div class="form-field">
                        <button class="full-width btn--primary">Enviar</button>
                        <div class="submit-loader">
                            <div class="text-loader">Enviando...</div>
                            <div class="s-loader">
                                <div class="bounce1"></div>
                                <div class="bounce2"></div>
                                <div class="bounce3"></div>
                            </div>
                        </div>
                    </div>

                    </fieldset>
                </form>

                <!-- contact-warning -->
                <div class="message-warning">
                    ¡Algo ocurrió! Por favor, intenta de nuevo.
                </div> 

                <!-- contact-success -->
                <div class="message-success">
                    ¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br>
                </div>

            </div> <!-- end contact-primary -->

As I mentioned before, I am getting the Failed to load resource: the server responded with a status of 404 (Not Found) error and I am not really sure why. If you can give me some insight, that would be amazing!

Thank you in advance for all of your help!!

You may want to try postman to post a form data instead of using a browser. If you do that, you can find out if your PHP code works fine or not, then focus on the JavaScript code.

I did some changes to your code yes that code was not working i sorted the same on my localhost Please compare the code:

Updated code: ( Html and js code)

  $(document).ready(function () { /* local validation */ $('#contactForm').validate({ /* submit via ajax */ submitHandler: function(form) { var sLoader = $('.submit-loader'); $.ajax({ type: "POST", url: "process.php", data: $(form).serialize(), beforeSend: function() { sLoader.slideDown("slow"); }, success: function(msg) { // Message was sent if (msg == 'OK') { sLoader.slideUp("slow"); $('.message-warning').fadeOut(); $('#contactForm').fadeOut(); $('.message-success').fadeIn(); } // There was an error else { sLoader.slideUp("slow"); $('.message-warning').html(msg); $('.message-warning').slideDown("slow"); } }, error: function() { sLoader.slideUp("slow"); $('.message-warning').html("Algo ocurrió. Por favor, inténtalo de nuevo"); $('.message-warning').slideDown("slow"); } }); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script> <div class="row section-header" data-aos="fade-up"> <div class="col-full"> <h1 class="display-2 display-2--light">Cuéntanos un poco más de tí para que empieces a vivir la experiencia Tech Consultant</h1> </div> </div> <div class="row contact-content" data-aos="fade-up"> <div class="contact-primary"> <h3 class="h6">Envíanos un mensaje</h3> <form name="contactForm" id="contactForm" method="post" novalidate="novalidate"> <fieldset> <div class="form-field"> <input name="contactName" type="text" id="contactName" placeholder="Nombre" value="" minlength="2" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="" aria-required="true" class="full-width"> </div> <div class="form-field"> <input name="contactSubject" type="text" id="contactSubject" placeholder="Asunto" value="" class="full-width"> </div> <div class="form-field"> <textarea name="contactMessage" id="contactMessage" placeholder="¿Qué es lo que más te interesa de Tech Consultant?" rows="10" cols="50" required="" aria-required="true" class="full-width"></textarea> </div> <div class="form-field"> <button class="full-width btn--primary">Enviar</button> <div class="submit-loader"> <div class="text-loader">Enviando...</div> <div class="s-loader"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div> </div> </div> </div> </fieldset> </form> <!-- contact-warning --> <div class="message-warning"> ¡Algo ocurrió! Por favor, intenta de nuevo. </div> <!-- contact-success --> <div class="message-success"> ¡Hemos recibido tu mensaje! Nuestros asesores se pondrán en contacto contigo<br> </div> </div> <!-- end contact-primary --> 

 **Php Updated code** <?php // Replace this with your own email address $siteOwnersEmail = 'your email id'; if($_POST) { $message = ""; $name = trim(stripslashes($_POST['contactName'])); $email = trim(stripslashes($_POST['contactEmail'])); $subject = trim(stripslashes($_POST['contactSubject'])); $contact_message = trim(stripslashes($_POST['contactMessage'])); $error = array(); // Check Name if (strlen($name) < 2) { $error['name'] = "Por favor, coloca tu nombre."; } // Check Email if (!preg_match('/^[a-z0-9&\\'\\.\\-_\\+]+@[a-z0-9\\-]+\\.([a-z0-9\\-]+\\.)*+[az]{2}/is', $email)) { $error['email'] = "Por favor, pon un correo válido."; } // Check Message if (strlen($contact_message) < 15) { $error['message'] = "Por favor, coloca tu mensaje"; } // Subject if ($subject == '') { $subject = "Contact Form Submission"; } // Set Message $message .= "Email from: " . $name . "<br />"; $message .= "Email address: " . $email . "<br />"; $message .= "Message: <br />"; $message .= $contact_message; $message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />"; // Set From: header $from = $name . " <" . $email . ">"; // Email Headers $headers = "From: " . $from . "\\r\\n"; $headers .= "Reply-To: ". $email . "\\r\\n"; $headers .= "MIME-Version: 1.0\\r\\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\\r\\n"; if (!$error) { //ini_set("sendmail_from", $siteOwnersEmail); // for windows server $mail = mail($siteOwnersEmail, $subject, $message, $headers); if ($mail) { echo "OK"; } else { echo "Oops! Algo ocurrió, por favor inténtalo de nuevo."; } } # end if - no validation error else { $response = (isset($error['name'])) ? $error['name'] . "<br /> \\n" : null; $response .= (isset($error['email'])) ? $error['email'] . "<br /> \\n" : null; $response .= (isset($error['message'])) ? $error['message'] . "<br />" : null; echo $response; } # end if - there was a validation error } ?> 

Let me know if you need zip for running code will send you the same:

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM