Skip to content

Instantly share code, notes, and snippets.

@dan-diaz
Created April 14, 2014 18:27
Show Gist options
  • Select an option

  • Save dan-diaz/10671736 to your computer and use it in GitHub Desktop.

Select an option

Save dan-diaz/10671736 to your computer and use it in GitHub Desktop.
AJAX Form w/ PHP response
$('#main-form').submit(function(e) {
e.preventDefault();
var name = $('#main-form #name-input').val();
var email = $('#main-form #email-input').val();
var formData = {};
var alertElement = $('#main-form .alert');
alertElement.removeClass('alert-success alert-danger');
var alertClass = '';
var alertText = '';
var showAlert = function(alertClass, alertText) {
alertElement
.addClass(alertClass)
.text(alertText)
.show();
};
// super basic validation
if((name && email) !== '') {
formData.name = name;
formData.email = email;
formData.website = window.location.pathname;
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
success: function(data) {
var response = JSON.parse(data);
if(response.failure){
alertClass = 'alert-danger';
if(response.failure) {
alertText += response.failure;
}
if(response.name) {
alertText += ' '+response.name;
}
if(response.email) {
alertText += ' '+response.email;
}
} else if(response.success) {
alertClass = 'alert-success';
alertText = response.success;
}
showAlert(alertClass, alertText);
},
error: function() {
showAlert('alert-danger', 'Sorry. Something went wrong. Your message was not received.');
}
});
var timer = setTimeout(function() {
clearTimeout(timer);
alertElement
.removeClass('alert-success alert-danger')
.text('')
.hide();
}, 10000);
return false;
}
});
<?php
if( isset($_POST) ) {
$recipient = "";
$subject = "I registered for an exclusive preview";
//form data
$name = strip_tags($_POST["name"]);
$email = strip_tags($_POST["email"]);
$website = strip_tags($_POST["website"]);
$response = array();
$valid = true;
//basic validation
if($name == "") {
$response["name"] = "Please enter a name";
$valid = false;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["email"] = "Invalid email address";
$valid = false;
}
if($valid == true) {
//send email
$headers = "From: {$website} form submission" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$emailbody = "<p><strong>Name: </strong> {$name} </p>";
$emailbody .= "<p><strong>Email Address: </strong> {$email} </p>";
mail($recipient,$subject,$emailbody,$headers);
$response["success"] = "Your message has been received. Thank you.";
// $response[] = "success" => "Your message has been received. Thank you.";
} elseif($valid == false) {
//deliver error message
$response["failure"] = "Your information is invalid.";
// $response[] = "failure" => "Your information is invalid.";
}
echo json_encode($response);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment