Perform two task with jQuery and php - javascript

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.

Related

mouse click not working on google recaptcha checkbox part of form

I have a issue with a form that has v2 checkbox for I'm not a robot, the mouse clicks don't seem to be working any more when trying to check the I'm not a robot checkbox, I can tab to it and press the enter key and it works but the google recaptcha checkbox is not detecting the mouse click any more for some reason. It's a new issue on me, has anyone else had this issue and how can I solve it as I don't understand this issue as was working all ok up until now
Thank you in advance, I can provide code but as am unsure what the issue is, I didn't want to post a lot of code that was not needed to post, below is the code I have
<?php
$postData = $statusMsg = '';
$status = 'error';
// If the form is submitted
if(isset($_POST['submitfooterform'])){
$postData = $_POST;
// Validate form fields
if(!empty($_POST['name']) && !empty($_POST['email']) &&
!empty($_POST['phone']) && !empty($_POST['message'])){
// Validate reCAPTCHA box
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-
recaptcha-response'])){
// Google reCAPTCHA API secret key
$secretKey = '';
// Verify the reCAPTCHA response
$verifyResponse =
file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
// Decode json data
$responseData = json_decode($verifyResponse);
// If reCAPTCHA response is valid
if($responseData->success){
// Posted form data
$name = !empty($_POST['name'])?$_POST['name']:'';
$email = !empty($_POST['email'])?$_POST['email']:'';
$phone = !empty($_POST['phone'])?$_POST['phone']:'';
$message = !empty($_POST['message'])?$_POST['message']:'';
// Send email notification to the site admin
$to = '';
$subject = 'New Website Enquiry';
$htmlContent = "
<h3>Contact Form Details</h3>
<br><br>
<p><b>Name: </b>".$name."</p>
<p><b>Email: </b>".$email."</p>
<p><b>Phone: </b>".$phone."</p>
<p><b>Message: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:'.$name.' ' . "\r\n";
// Send email
#mail($to,$subject,$htmlContent,$headers);
$status = 'success';
$statusMsg = header("Location: ../enquiry-confirmation.php");
$postData = '';
}else{
$statusMsg = "<strong>" . 'Robot verification failed, please try again.' . "</strong>";
}
}else{
$statusMsg = "<strong>" . 'Please check on the reCAPTCHA box.' . "</strong>";
}
}else{
$statusMsg = 'Please fill all the mandatory fields.';
}
}
?>
<form class="needs-validation" action="includes/footer.php" method="post" name="contact-form">
<div class="form-row">
<div class="col-md-6 mb-3">
<input type="text" class="form-control" placeholder="Name" required name="name" value="<?php echo !empty($postData['name'])?$postData['name']:''; ?>">
</div>
<div class="col-md-6 mb-3">
<input type="text" class="form-control" placeholder="Email Address" required name="email" value="<?php echo !empty($postData['email'])?$postData['email']:''; ?>">
</div>
<br><br>
<div class="col-md-12 mb-3">
<input type="text" class="form-control" placeholder="Phone Number" name="phone" value="<?php echo !empty($postData['phone'])?$postData['phone']:''; ?>">
</div>
<div class="col-md-12 Textarea-btn">
<textarea class="form-control mb-3" id="exampleFormControlTextarea1" rows="5" placeholder="Your message..." name="message" required><?php echo !empty($postData['message'])?$postData['message']:''; ?></textarea>
</div>
<div class="col-md-12 mb-3">
<div class="g-recaptcha" data-callback="recaptchaCallbackftr" data-sitekey=""></div>
</div>
<div class="col-md-12 Textarea-btn">
<button id="submitBtnftr" class="btn btn-dark btn-dark-animated" type="submit" name="submitfooterform" disabled>Send Message</button>
</div>
</div><!-- Form Row /-->
</form>

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

Contact form that doesn't refresh page on submit while using Wordpress

I have setup the following code to make a contact form that doesn't refresh the page when submitted.
HTML:
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="form-action">
</form>
JavaScript/AJAX request:
$("#contact-form").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = "<?php echo get_template_directory_uri(); ?>/library/contact-form.php";
var posting = $.post( url, {
name: $('#name').val(),
email: $('#email').val(),
subject: $('#subject').val(),
message: $('#message').val(),
});
posting.done(function( data ) {
alert('success');
});
});
PHP:
// Set $to as the email you want to send the test to.
$to = "my#email.com";
// Email subject and body text.
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$headers .= "Reply-To: ". strip_tags($_POST['email']) . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = $_POST["message"];
// send test message using wp_mail function.
if(isset(($_POST['name']), ($_POST['email']), ($_POST['message']), ($_POST["subject"]))) {
$sent_message = wp_mail( $to, $subject, $message, $headers );
} else {
};
//display message based on the result.
if ( $sent_message ) {
// The message was sent.
echo 'The test message was sent. Check your email inbox.';
} else {
// The message was not sent.
echo 'The message was not sent!';
}
The code works when I run it on my local website, It returns the success alert.
The PHP code also succeeds in sending the contact form information to my email address.
I get a 'the server responded with a status of 500 (internal error)' when I run it on my web server.
I think I must have overlooked something stupid here but I can't see it and hoping someone else can see it and help me out?
Thanks in advance!
This is how i do my ajax submission for a form. It's contains WordPress security measures, you can learn them from google in detail but small description will be provided by me.
HTML
<form method="POST" id="contact-form">
<div class="contact-element flex-row">
<input class="" type="text" name="name" placeholder="Name" id="name" Required>
<input class="" type="text" name="email" placeholder="Email Address" id="email" Required>
</div>
<input class="" type="text" name="subject" placeholder="Subject" id="subject" Required>
<textarea type="text" name="message" rows="5" placeholder="Message" id="message" Required></textarea>
<input class="contact-submit" id="submit" name="submit" type="submit" value="Submit">
<input type="hidden" name="action" value="contact_form" id="cf_action" url="<?= admin_url('admin-ajax.php'); ?>">
<?php wp_nonce_field( 'contact_form', 'contact_form_wpnonce' ); ?>
</form>
Javascript
jQuery(function($){
$("#contact-form").submit(function(e){
var url = $('#cf_action').attr('url');
$.ajax({
type: "POST",
url: url,
data: $("#contact-form").serialize(),
success: function(data) {
alert(data.data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
Function
add_action('wp_ajax_contact_form', 'contact_form_function');
add_action('wp_ajax_nopriv_contact_form', 'contact_form_function');
function contact_form_function()
{
if ( !isset($_POST['xyz_contact_email_meta_box_nonce']) && !wp_verify_nonce($_POST['xyz_contact_email_meta_box_nonce'], 'xyz_save_contact_email_data')) {
# code...
return;
}
$user_name = sanitize_text_field( $_POST['name'] );
$user_email = sanitize_email( $_POST['email'] );
$user_subject = sanitize_text_field( $_POST['subject'] );
$user_message = sanitize_textarea_field( $_POST['message'] );
$to = 'xyz#gmail.com';
$subject = $user_subject;
$body = 'Hi you recived a message from '.$user_name.'('.$user_email.'),<p>'.$user_message.'</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$status = wp_mail( $to, $subject, $body, $headers );
if($status){
wp_send_json_success('sent successful');
}else{
wp_send_json_error('something went wrong');
}
}
Description
okay let me guide through WordPress a bit.
WordPress have already inbuilt functionality to handle ajax-request from it's theme's functions.php, you have to copy and paste html code where you want form to show, js code in footer and function code in functions.php
Here are some tips:-
wp_nonce_field = it's used for security purpose and prevent hackers to use form for different purpose.
Sanitize data to make sure you are not receiving any malicious code from your posted data, you can use esc_attr(it will convert any tags and script into html) too.
It's a good habit to send data back with WordPress default function wp_send_json_success & wp_send_json_error.
(Forgive me if you feel hard to understand since it's my first answer on stackoverflow)
Cheers!!

PHP,jQuery,HTML form with ajax is not working

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

Html form refuses to be submitted via JQuery

So I was following an AJAX/JQuery tutorial for a registration script that will be acted upon by PHP/MySQL and will be submitted via JQuery.
Now the problem that I'm encountering is that the form submits directly to the action page, which should not be so, as it supposed to submit to script.js Here are the html code for the form.
<form method="post" id="register-form" action="transact-user.php">
<h2 class="form-signin-heading"></h2>
<div class="form-group">
<div class='row'>
<div class='col-sm-6'>
<input type='text' class='form-control' id='fname' name='fname' placeholder="First name">
</div>
<div class='col-sm-6'>
<input type='text' class='form-control' id='lname' name='lname' placeholder="Last name">
</div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number" name = "phone" id = "phone" >
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email address" name = "email" id ="email">
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name = "password" id = "password">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password Again" name = "confirmpassword" id = "confirmpassword">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block btn-apply" type="submit" name="btn-save" id = "btn-submit"><span class="glyphicon glyphicon-log-in"></span> Register</button>
</div>
</form>
</div> <!-- /container -->
<div id = "ack"></div>
script.js
$("button#btn-submit").click(function()
{ /* validation */
/* form submit */
if ($("fname").val()=="" || $("lname").val()=="" )
$("div#ack").html("Please enter both your first name and your surname");
else
$.post($("#register-form").attr("action"),
$("#register-form: input").serializeArray(),
function(data){
$("div#ack").html(data);
});
$("#register-form").submit(function(){
return false;
})
/* form submit */
});
Finally, this is the action php script transact-user.php
<?php
if($_POST)
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$confirmpassword = $_POST['confirmpassword'];
if($email != '') {
$qry = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($mysqli,$qry);
if($result) {
if(mysqli_num_rows($result) > 0) {
echo "Email already in use";
}
#mysqli_free_result($result);
}
else {
die("Query failed");
}
}
$activation = md5(uniqid(rand(), true));
if ($stmt = "INSERT INTO users(firstname, lastname, email, password, verification, phone)"
." values('$fname', '$lname', '$email', '$password', "
. "'$activation','$phone')" or
die("Could not perform query ".mysqli_error($mysqli))) {
$result = mysqli_query($mysqli, $stmt)
or die("The system could not register you"
. "".mysqli_error($mysqli) . "<br>" . $stmt);
if ($result){
echo "sent";
}
//echo "<a href=\"gethotel.php?hid=".$row['hotel_id'].
//
/* close statement */
//$stmt->close();
}
}
?>
The issue us because you are hooking to the click event of the submit button and are not preventing the event from completing.
Also note that your selector to build the querystring is incorrect, as there should be a space before the : and not between the : and input, eg $("#register-form :input")
To fix the issues hook to the submit event of the form and use preventDefault(). Try this:
$("#register-form").submit(function(e) {
e.preventDefault();
if ($("fname").val().trim() == "" || $("lname").val().trim() == "") {
$("div#ack").html("Please enter both your first name and your surname");
} else {
$.post(this.action, $(this).find(':input').serializeArray(), function(data) {
$("div#ack").html(data);
});
}
});

Categories

Resources