ajax contact form does not send email - javascript

All day i trying to solve the problem but without success.
The form does not send a message and not written an error.
form.html
<div class="ok" id="ok"></div>
<div id="data">
<div id="alert" class="alert_ig"></div>
<form id="form" class=" clearfix" method="POST" action="">
<div class="col-sm-12">
<div class="form-group">
<input name="name" type="text" id="name" value="{$smarty.cookies.nameuser}" class="form-control" placeholder="Name"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input name="email" type="email" id="email" value="{$smarty.cookies.emailuser}" class="form-control" placeholder="E-mail"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<textarea id="message" class="form-control" rows="5" name="text" placeholder="Message"></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<button style="margin-top:10px" id="submit" type="submit" class="bot_g">Send</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#submit').click(function(e){
var form = $(this);
var error = false;
if (!error) {
var data = form.serialize();
$.ajax({
type: 'POST',
url: '{$home}/system/modules/contacts/send.php',
dataType: 'json',
data: data,
success: function(data){
if (data.error.length > 0) {
$('#alert').html(""+data['error']+"");
$('#email').addClass("fill");
} else {
$('#ok').html('send.');
$( "#data" ).css( "display","none" );
}
},
return false;
)};
});
</script>
</div>
send.php
<?php
require_once '../../inc/core.php';
$name=Text(trim($_POST['name']));
$email=Text(trim($_POST['email']));
$subject=Text(trim($_POST['subject']));
$text=Text(trim($_POST['text']));
if(empty($name)){
$json['error'] = 'Come on, you have a name don\'t you?';
echo json_encode($json);
exit;
}
if (mb_strlen($name) < 2 || mb_strlen($name) > 250){
$json['error'] = 'Your name must consist of at least 2 characters!';
echo json_encode($json);
exit;
}
if(empty($email)){
$json['error'] = 'No Email, No Message!';
echo json_encode($json);
exit;
}
if (mb_strlen($email) < 5 || mb_strlen($email) > 64){
$json['error'] = 'Your email must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$json['error'] = 'Unknown characters in your e-mail!';
echo json_encode($json);
exit;
}
if(empty($subject)){
$json['error'] = 'Um...yea, you have to write something to send this form.';
echo json_encode($json);
exit;
}
if (mb_strlen($subject) < 5 || mb_strlen($subject) > 250){
$json['error'] = 'Your subject must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (mb_strlen($text) < 2 || mb_strlen($text) > 10000){
$json['error'] = 'Thats All? Really?';
echo json_encode($json);
exit;
}
$mailer = new phpmailer();
$mailer->ContentType = "text/html";
$mailer->From = $email;
$mailer->Subject = 'New message from '.$home;
$mailer->Body ="Subject: ".$subject."<br/>
Name: ".$name."<br/>
E-mail: ".$email."<br/>
".nl2br($text);
$mailer->AddAddress($setup['emailadmin'], '');
$mailer->Send();
$json['error'] = 0;
echo json_encode($json);
?>
When is my problem with this code?
I must use this send.php format, but may to change ajax and html form to working...
thanks

var form = $(this);
In this line $(this); refers to the submit button so var form, stores your submit button instead of the form element itself.
You may not see an error on the client-side, but if you try to debug the data sent to your server-side you will see something is wrong.
Try replacing $(this) with the selector that matches your form element.
Also, if you want to inform your users when the server returns an error like a 500 error for example, you can add an error callback to your $ajax function, along with the success callback you already have.
Have a look here http://api.jquery.com/jquery.ajax/ for the documentation.
Also add e.preventDefault() at the end of your event handler, to prevent the default action of submitting the form if you want to do an ajax submit.

Related

How to return JSON in HTML using PHP and AJAX without redirecting?

I have searched a lot for a solution to this problem but I have not found one for it. I am trying to include a form for sending e-mails (a contact us form) on my site (using Bootstrap). PHP is being used for the mailer model.
The problem lies in the message that should appear to the user when the message is sent, the message does not appear in the place assigned to it(#status), but rather I am directed to a new page with array data.https://drive.google.com/file/d/1tH8cVCWpx7pDe2OyxkGSKY6rnqV9KxlL/view?usp=sharing
Note that the message appears in all verification cases (when name or email or subject or message fields is empty), only when the email is sent, it directs me to another page!https://drive.google.com/file/d/1lK11R2a18S2arExDegcZyOnITwRlIOYh/view?usp=sharing
Here is my code:
< script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" > < /script> <
script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" > < /script> <
script >
function validateForm() {
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
'subject': $('input[name=subject]').val(),
'message': $('textarea[name=message]').val()
};
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
dataType: "json",
success: function(data, textStatus, jqXHR) {
$('#status').text(data.message1);
if (data.code) //If mail was sent successfully, reset the form.
$('#contact-form').closest('form').find("input[type=text], textarea").val("");
},
error: function(jqXHR, textStatus, errorThrown) {
$('#status').text(jqXHR);
}
});
} <
/script>
<div class="col-lg-8">
<form id="contact-form" name="contact-form" action="mail.php" method="POST">
<div class="row ">
<div class="form-group col-md-6">
<input class="form-control" placeholder="Name" id="name" name="name" required="required">
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" placeholder="Email" id="email" name="email" required="required">
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" placeholder="Subject" id="subject" name="subject" required="required">
</div>
<div class="form-group col-md-12">
<textarea type="text" class="form-control" rows="6" placeholder="Message" id="message" name="message" required="required"></textarea>
</div>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-lg btn-primary ml-auto" onclick="validateForm();">Send Message</button>
</div>
<div class="status" id="status"></div>
</form>
</div>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
header('Content-Type: application/json');
$data = array();
if ($name === ''){
$data['message1'] = 'Name cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($email === ''){
$data['message1'] = 'Email cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$data['message1'] = 'Email format invalid.';
$data['code'] = 0;
print json_encode($data);
exit();
}
}
if ($subject === ''){
$data['message1'] = 'Subject cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
if ($message === ''){
$data['message1'] = 'Message cannot be empty.';
$data['code'] = 0;
print json_encode($data);
exit();
}
$content="From: $name \nEmail: $email \nMessage: $message";
$recipient = "******#gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
$data['message1'] = 'Email successfully sent!';
$data['code'] = 1;
print json_encode($data);
exit();
?>
The problem you experience is that upon the form's submission's default behavior is the behavior you usually see when browsers are interacting with the HTTP protocol. Your button is of type submit and it submits the form.
Assuming that you handle all the logic that you want inside validateForm, the thing your code is missing is that your intention is to prevent the default behavior on submit:
$("#contact-form").submit(function(e) {
e.preventDefault();
});

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

Displaying form confirmation message on form submit

Thought you might be able to help with this, as I sort of know what I want and how to do it but I am not overally familiar with AJAX/JS and after a certain point I just stopped taking stuff in.
Basically, I am trying to have some text appear when a user submits a form, but obviously only when the form is successfully sent. My HTMl and PHP are below, but I have no idea what I am doing beyond this point so maybe someone can give me a little hand.
<form name="contactform" action="includes/contactprocess.php" method="post">
<div class="form-group">
<input type="text" class="form-control" id="fname" name="fname" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="sname" name="sname" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" required placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" required placeholder="Message Subject">
</div>
<div class="form-group">
<textarea rows="3" name="comment" class="form-control" required placeholder="Enter Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the PHP thus far:
<?php
/* Set e-mail recipient */
$myemail = "myemailhere";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$sname = check_input($_POST['sname'], "Enter your second name");
$subject = check_input($_POST['subject'], "Enter the message subject");
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Enter the message you wish to be sent");
/* Error handling and sanitisation for email */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("The e-mail you have entered is not valid");
}
/* Let's prepare the message for the e-mail */
$message = "A contact form has been submitted by;
Name: $fname
Surname: $sname
E-mail: $email
Comments:
$comment
Message sent via myemailhere
";
/* Send message via mail function */
mail($myemail, $subject, $message);
if(mail($myemail, $subject, $message)) {
$data['success'] = true;
}
else{
$data['success'] = false;
}
// convert the $data to json and echo it
// so jQuery can grab it and understand what happend
echo json_encode($data);
/* Check input */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
The JS/AJAX I don't really understand:
<script>
$(document).ready(function() {
// hide the success message
$('#success').hide();
// process the form
$('form').submit(function(event) {
// get the form data before sending via ajax
var formData = {
'name' : $('input[name=name]').val(),
'number' : $('input[name=number]').val(),
'message' : $('input[name=message]').val(),
'contactSubmit' : 1
};
// send the form to your PHP file (using ajax, no page reload!!)
$.ajax({
type: 'POST',
url: 'file.php', // <<<< ------- complete with your php filename (watch paths!)
data: formData, // the form data
dataType: 'json', // how data will be returned from php
encode: true
})
// JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
// only after that, we´ll continue
.done(function(data) {
if(data.success === true) {
// show the message!!!
$('#success').show();
}
else{
// ups, something went wrong ...
alert('Ups!, this is embarrasing, try again please!');
}
});
// this is a trick, to avoid the form submit as normal behaviour
event.preventDefault();
});
});
</script>

How can i submit hidden values to php using AJAX

i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

Categories

Resources