Jonathan Jonathan - 5 months ago 16
jQuery Question

php jQuery form work until I added the ajax

I am trying to make this form as simple as possible with a bit of jQuery validation and php validation using ajax. Everything was working fine until I tried to include the ajax.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">

<script type="text/javascript">
// we will add our javascript code here
jQuery(document).ready(function($) {

$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();

$.ajax({
type: "POST",
url: "contactfinal.php",
data: str,
success: function(msg) {
if(msg == 'OK') {
result = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';
$("#fields").hide();
} else {
result = '<div class="alert alert-danger" role="alert"><p><strong>There were error(s) in your form:</strong></p>' + error + '</div>';
}

}
});
return false;
});
});
</script>
</head>
<body>

<div class="container">

<h1>Get in touch!</h1>

<div id="error"><? echo $error.$successMessage; ?></div>

<form id="ajax-contact-form" action="">
<fieldset class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
<small class="text-muted">We'll never share your email with anyone else.</small>
</fieldset>
<fieldset class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject" >
</fieldset>
<fieldset class="form-group">
<label for="exampleTextarea">What would you like to ask us?</label>
<textarea class="form-control" id="content" name="content" rows="3"></textarea>
</fieldset>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>

</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>




</body>
</html>


contactfinal.php

<?php

$error = ""; $successMessage = "";

if ($_POST) {

if (!$_POST["email"]) {

$error .= "An email address is required.<br>";

}

if (!$_POST["content"]) {

$error .= "The content field is required.<br>";

}

if (!$_POST["subject"]) {

$error .= "The subject is required.<br>";

}

if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {

$error .= "The email address is invalid.<br>";

}

if ($error != "") {

$error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>';

} else {

$emailTo = "me@mydomain.com";

$subject = $_POST['subject'];

$content = $_POST['content'];

$headers = "From: ".$_POST['email'];

if (mail($emailTo, $subject, $content, $headers)) {

$successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';


} else {

$error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>';


}

}



}

?>

Answer

The problem is that you are trying to execute jQuery script before even loading the jQuery library. Try to move the whole jQuery jQuery(document).ready() snippet right after loading the bootstrap.min.js file and everything would work fine.

Not sure if you are there yet, but the PHP part doesn't return any response. You should use echo $successMessage and echo $error if you want to be able to append the error/success messages from the AJAX response.

You should either echo the response as it is, or more advanced, you can json_encode it in array -

<?php

    $error = ""; $successMessage = "";

    if ($_POST) {

        if (!$_POST["email"]) {

            $error .= "An email address is required.<br>";

        }

        if (!$_POST["content"]) {

            $error .= "The content field is required.<br>";

        }

        if (!$_POST["subject"]) {

            $error .= "The subject is required.<br>";

        }

        if ($_POST['email'] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {

            $error .= "The email address is invalid.<br>";

        }

        if ($error != "") {

            $error = '<div class="alert alert-danger" role="alert"><p>There were error(s) in your form:</p>' . $error . '</div>';

            echo $error;

        } else {

            $emailTo = "me@mydomain.com";

            $subject = $_POST['subject'];

            $content = $_POST['content'];

            $headers = "From: ".$_POST['email'];

            if (mail($emailTo, $subject, $content, $headers)) {

                $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';

                echo $successMessage;


            } else {

                $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>';

                echo $error;


            }

        }



    }

?>

Next, since the server is returning the message, you can just append the response in the error holder

<script type="text/javascript">                                 
// we will add our javascript code here
jQuery(document).ready(function($) {

    $("#ajax-contact-form").submit(function() {
        var str = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "contactfinal.php",
            data: str,
            success: function(response) {

                $('#error').html(response);

            }
        });
        return false;
    });
});
</script> 

This part <div id="error"><? echo $error.$successMessage; ?></div> is invalid, because you are trying to print javascript string into PHP. If you are following the AJAX snippet I above, you can simply replace that part with an empty div <div id="error"></div>

Comments