PHP,jQuery,HTML form with ajax is not working - javascript

I'm trying to submit form data to php script with jQuery .post() method,than to receive php script data back and display it on form page,but it doesnt work.Also I'm using jQuery validate plugin for client side validation as well.Here is my code:
Html:
<div class="contact-form">
<button class="contact-close">X</button>
<form method="post" action="formular.php" id="quote-form">
<div id="returned"></div>
<div class="houndred">
<input type="text" name="name" placeholder="Name*" class="input-half" id="name" min-width="2" autofocus required>
<input type="email" name="email" placeholder="Email*" class="input-half" id="email" required>
<input type="text" name="subject" placeholder="Subject" class="input-half" id="subject" required>
<input type="url" name="url" placeholder="Website" class="input-half" id="website">
</div>
<div class="houndred">
<textarea name="message" class="textarea" id="message" placeholder="message*" required></textarea>
<br><p></p>
</div>
<div class="eightytwo">
<button id="quote-button">Send</button>
</div>
<div id="summary"></div>
</form>
</div><!-- .padding-fix -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="js/validation.js"></script>
<script src="js/ajaxform.js"></script>
JS for posting:
$(document).ready(function(){
$('form').on('submit', function(event) {
event.preventDefault();
$.post('formular.php', $(this).serialize(), function(data)) {
var dataForm = data;
$("#returned").append(dataForm);
}
});
)};
and PHP:
if(!empty($_POST)) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$url = $_POST['url'];
$message = $_POST['message'];
if(empty($name) || empty($email) || empty($subject) || empty($url) || empty($message)) {
$errors[] = 'All fields are required!';
} else {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if(ctype_alpha($name === false)) {
$errors[] = 'Name can only contain letters';
}
if (ctype_alpha($subject === false)) {
$errors[] = 'Subject can only contain letters';
}
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) === false) {
$errors[] = 'Please enter a valid url address with http in front';
}
if(empty($message)) {
$errors[] = 'Please enter a message';
}
}
if(!empty($errors)) {
echo '<ul style=\"list-style: circle; color: #f74d4e\">';
foreach($errors as $error) {
echo '<li style=\"color: #f74d4e;\"' . $error . '</li>';
}
echo '</ul>';
}
$send_message = 'From:' . $url . '<br>' . strip_tags(addslashes($message));
if(empty($errors)) {
mail('something#something.com', $subject, $send_message , $email);
echo '<h4 style=\"color: #f74d4e;\">Thank you for contacting me!</h4>';
exit();
}
}
I'm hoping that this makes sense,to me it had,but I'm strugling with it for last couple of hours,still trying to figure out what went wrong,I also tryed posting with $.ajax() and no response.One more thing,form is geting loaded using jquery .load() method to popup box,that is why it is important to me to do it with ajax

From a cursory inspection of your code, it seems that you have added an extra closing parentheses in this line, like so: function(data))
$.post('formular.php', $(this).serialize(), function(data)) {
try
$.post('formular.php', $(this).serialize(), function(data) {
instead
HTH

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();
});

Email successfully sent and i received the mail but the status of button and form has no change

this is my first time to ask here, i hope i can find a solution regarding my problem. (Note: i am not a good in ajax but i can understand as much as i can .. just have more research.
below is my problem:
my Email successfully sent and i received the mail but the status of button and form has no change.. the caption of submit button did not back to normal and just like no happened at aenter code herell.. just says.. Sending... (the caption of button after submit the form)
FYI: i'll just modified this code from different source in order to work in my form.. i add captcha on it which is not include from the email codes. below is the whole codes.
| the html form
<h3>
<font color="#2E86C1">Contact form.</font>
</h3>
<div id="success_message" style="width:100%; height:100%; display:none; ">
<h3>Posted your message successfully!</h3>
</div>
<div id="error_message" style="width:100%; height:100%; display:none; ">
<h3>Error</h3> Sorry there was an error sending your form.
</div>
<form class="customform" role="form" method="post" id="reused_form">
<div class="s-12">
<input name="name" placeholder="Your name" title="Your name" type="text" required />
</div>
<div class="s-12">
<input name="email" placeholder="Your e-mail" title="Your e-mail" type="email" required />
</div>
<div class="s-12">
<input name="phone" placeholder="Your phone" title="Your phone" type="text" required />
</div>
<div class="s-12">
<input name="subject" placeholder="Subject" title="Your subject" type="text" required />
</div>
<div class="s-12">
<textarea placeholder="Your message" name="message" rows="5" required></textarea>
</div>
<!--<form method="GET"> -->
<img src="captcha.php" id="captcha" />
<!-- CHANGE TEXT LINK -->
<a href="javascript:void(0);" onclick="
document.getElementById('captcha').src='captcha.php?'+Math.random();
document.getElementById('captcha-form').focus();" id="change-image"><br>
Not readable? Change text.
</a><br />
<input type="text" required style="height: 40px; width: 200px; font-size: 18px;" placeholder="Enter codes here" name="captcha" id="captcha" autocomplete="off"><br />
<div class="s-12 m-12 l-4"><button class="color-btn" type="submit">Submit Button</button></div>
</form>
|the php mail code:
<?php session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mail_to = "myemail#domain.com";
# Sender Data `enter code here`
$subject = trim($_POST["subject"]);
$name = str_replace(array("\r", "\n"), array(" ", " "), strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = trim($_POST["phone"]);
$message = trim($_POST["message"]);
$captcha = trim($_POST["captcha"]);
if (empty($name) or !filter_var($email, FILTER_VALIDATE_EMAIL) or empty($phone) or empty($subject) or empty($message)) {
# Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Please complete the form and try again.";
exit;
}
if (empty($_SESSION['captcha']) || trim(strtolower($captcha)) != $_SESSION['captcha']) {
unset($_SESSION['captcha']);
//$hasError = true;
// http_response_code(400);
echo "Captcha code not match try again.";
exit;
} else {
$captcha = trim($_POST['captcha']);
exit;
}
# Mail Content
$content = "Name: $name\n";
$content .= "Email: $email\n\n";
$content .= "Phone: $phone\n";
$content .= "Message:\n$message\n";
# email headers.
$headers = "From: $name <$email>";
# Send the email.
$success = mail($mail_to, $subject, $content, $headers);
if ($success) {
# Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
# Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong, we couldn't send your message.";
}
} else {
# Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
| the js code:
$(function () {
function after_form_submitted(data) {
if (data.result == 'success') {
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else {
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors, function (key, val) {
$('#error_message ul').append('<li>' + key + ':' + val + '</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function () {
$btn = $(this);
label = $btn.prop('orig_label');
if (label) {
$btn.prop('type', 'submit');
$btn.text(label);
$btn.prop('orig_label', '');
}
});
}//else
}
$('#reused_form').submit(function (e) {
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function () {
$btn.prop('type', 'button');
$btn.prop('orig_label', $btn.text());
$btn.text('Sending ...');
});
$.ajax({
type: "POST",
url: 'mail.php',
data: $form.serialize(),
success: after_form_submitted,
dataType: 'json'
});
});
});
i hope you can help me to fix the code .. since i am not an expert .. but eager to learn
Thanks in advance

Perform two task with jQuery and php

I have a form which a user fills in, the data is sent to my email, but I also wanted email to be posted to my mail chimp using api but it's not working at the moment.
Here is my form:
<form method="POST" onsubmit="return false;" id="dealerForm ">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input id="subject" name="subject" value="Dealer partner message" type="hidden">
<input class="form-control" placeholder="Your Name *" id="name" name="name" required="" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Email *" id="email" name="email" required="" type="email">
</div>
<div class="form-group">
<input class="form-control" placeholder="Your Phone *" id="phone" name="phone" required="" type="tel">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Dearlership Info *" id="message" name="message" required=""></textarea>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-right">
<button type="submit" class="btn send_msg">Send Message</button>
</div>
</div>
</form>
Here is my php with mail chimp api and mail send.
<?php
// Email address verification
function isEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
if($_POST) {
$mailchimp_api_key = 'myapikey'; // enter your MailChimp API Key
// ****
$mailchimp_list_id = 'mylistID'; // enter your MailChimp List ID
// ****
$subscriber_email = addslashes(trim($_POST['email']));
if(!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Not a valid email address!';
echo json_encode($array);
}
else {
$array = array();
$merge_vars = array();
require_once 'mailchimp/php/MailChimp.php';
$MailChimp = new \Drewm\MailChimp($mailchimp_api_key);
$result = $MailChimp->call('lists/subscribe', array(
'id' => $mailchimp_list_id,
'email' => array('email' => $subscriber_email),
'merge_vars' => $merge_vars,
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => true,
));
if($result == false) {
$array['valid'] = 0;
$array['message'] = 'An error occurred! Please try again later.';
}
else {
$array['valid'] = 1;
$array['message'] = 'Success! Please check your mail.';
}
echo json_encode($array);
}
}
if (isset($_POST["email#mail.com"])) {
$to = 'mail#mail.com';
$subject = $_POST['subject'];
$message = 'Name: '.$_POST["name"].'<br>Email: '.$_POST["email"].'<br>Phone: '.$_POST["phone"].'<br>Message: '.$_POST["message"];
$headers = 'From: ' . $_POST["email"] . "\r\n" .
'Reply-To: ' . $_POST["email"] . "\r\n" .
'Content-type: text/html; charset=iso-8859-1;';
if(mail($to, $subject, $message, $headers)){
echo "New record created successfully";
}
}
?>
While my JQuery code:
$("#dealerForm").on("submit", function(){
//debugger;
$.ajax({
type: 'POST',
var url;
url: "contact/dealer.php",
data: $("#dealerForm").serialize()
}).done(function (data) {
//debugger;
console.log(data);
window.location.href = "https://example.com/Thank%20You.html";
});
$("#dealerForm")[0].reset();
return false;
});
Thanks for your comment and your help.
Before mail-chimp fix I think you need to fix followings:
You don't need to use onsubmit="return false;" in form declaration. You already returned false in jQuery onsubmit. And also remove space from form ID name. So, your form declaration can be like <form method="POST" id="dealerForm">
Remove var url; from ajax
Now debug email/mailchimp code in dealer.php.

Contact Form opening PHP file instead of showing Popup

I have a contact form on my website that with the current code sends an email to the sender and the receiver, and all works fine. However, once completing the form, the page opens email.php instead of showing a popup that I hoped it would. I have no idea how to fix as I'm not used to writing for php and JS. Below is my code.
<form method="post" action="email.php" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_self" novalidate>
<input type="text" value="" name="full_name" class="fullname" id="mce-name" placeholder="full name" required>
<input type="text" value="" name="phone_num" class="phonenum" id="mce-phone" placeholder="phone number" required>
<br>
<input type="email" value="" name="email" class="email" id="mce-EMAIL" placeholder="email address" required>
<div style="position: absolute; left: -5000px;"><input type="text" name="b_cdb7b577e41181934ed6a6a44_e65110b38d" value=""></div>
<div class="clear"><input type="submit" value="Submit" name="submit" id="mc-embedded-subscribe" class="button"></div>
</form>
<?php
if(isset($_POST['submit'])){
$to = "email#help.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$full_name = $_POST['full_name'];
$phone_num = $_POST['phone_num'];
$subject = "Title";
$subject2 = "Copy of your form submission";
$message = "Message";
$message2 = "Message2";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2);
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
}
} else {
echo '<script>function displayPopup()
{
alert("Form submitted!");
}<script>';
}
}
?>
because you only declare the popup function, you did not run displayPopup()
try to change to
if ($_POST['submit']) {
if ($name != '' && $email != '' && $subject != '' && $message != '') {
} else {
echo '<script>function displayPopup(){alert("Form submitted!");}';
echo 'displayPopup();</script>
';
}
}

Contact form does not validate on an iphone

The following contact form is not validating when submitting from an iphone...
It can be previewed here: loaistudio.com/contact
When I tried to submit the form without felling the fields, it opened a new blank page showing number 1 only on the top left side "which is not suppose to do at all" and actually sent the form empty... It does not do that on desktop.
I played around with the code trying to find the issue but no idea where is the problem! please help.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_POST['name'])
&& isset($_POST['email'])
&& isset($_POST['message'])
&& isset($_POST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "EMAIL GOES HERE";
$subject = "New Message From: $name";
$message = "$message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = ( mail($to, $subject, $message, $headers) );
if( isset($_POST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
<!DOCTYPE html>
<html class="no-js">
<head>
<title>Contact us | Website</title>
</head>
<body>
<div class="wrapper" id="contactPage">
<div class="content">
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form action="contact.php" id="contactForm" method="post" name="contactForm">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" placeholder="Enter Name" required="" type="text">
</div>
<div class="email">
<p>Email Address</p>
<input name="email" placeholder="Enter Email" required="" type="email">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" required=""></textarea>
</div>
<button id="submit" type="submit">Send</button>
</form>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
</body>
</html>
you are adding jquery at the end of the html but you are using jquery before that, so javascript breaks with Uncaught ReferenceError: $ is not defined.
try moving this line to header:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$("#contactForm").submit(function(event) {
event.preventDefault();
$submit = $(this).find('button[id="submit"]');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.addClass("sent");
$submit.attr('disabled', 'disabled');
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
});
</script>
This is code You have added AND THEN INCLUDED JQUERY, :) SO USE JQUERY IN HEADER !

Categories

Resources