Reputation: 43
have tried to send a message for hours, the HTML:
<div id="contactform">
<div id="contact_results"></div>
<form name="contactform" method="POST" action="contact_me.php">
<input type="text" name="name">
<input type="text" name="telephone">
<input type="text" name="email">
<textarea rows="6" name="message"></textarea>
<input type="submit" value="SEND" id="submit_btn">
</form>
</div>
The JavaScript:
$(document).ready(function() {
$('form').on('submit', function (e) {
e.preventDefault();
//Rest of your code
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contactform input[required=true], #contactform textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
post_data = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'telephone' : $('input[name=telephone]').val(),
'msg' : $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contactform input[required=true], #contactform textarea[required=true]").val('');
$("#contactform .white-spacing").slideUp(); //hide form after success
}
$("#contactform #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input[required=true], #contactform textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
The contact_me.php:
<?php
if($_POST)
{
$to_email = "[email protected]";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$telephone = filter_var($_POST["telephone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(!filter_var($telephone, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email."\r\nPhone Number :". $telephone;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
}
?>
How can I get the site to send the AJAX request? It keeps getting stuck in the first PHP code, and returns 'Sorry Request must be Ajax POST'. I am running on the basic GoDaddy Linux server.
Thanks for all the JS experts!
Upvotes: 1
Views: 2398
Reputation: 6933
You are sending the form on click on the button #submit_btn. You need to prevent the default event for the submit button of the form.
With $_SERVER['HTTP_X_REQUESTED_WITH'] you are checking if the file is accessed via ajax request and because you are not sending it via ajax you get the error 'Sorry Request must be Ajax POST'.
So to prevent the form from actually being submitted on submit button click you need to add
$("#submit_btn").click(function(e) {
e.preventDefault();
//Rest of your code
});
You can also try it this way
$('form').on('submit', function (e) {
e.preventDefault();
//Rest of your code
});
You can run your code on form submit instead of the submit button click.
Upvotes: 4