Integrating reCAPTCHA v2 to existing form - recaptcha

I'm having troubles integrating reCAPTCHA v2 with my existing form. I would be grateful if someone has the solution to this.
This is my form page HTML code where I'm adding the widget:
before /head tag:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
In the body:
<div class='mod modContactForm'>
<form method="post" action="send.php" accept-charset="UTF-8"><p>
<label for='name'>Your Name</label>
<input class="input-text required" id="name" name="name" type="text" />
</p>
<p>
<label for='email'>Your Email</label>
<input class="input-text required email" id="email" name="email" type="text" />
</p>
<p>
<label for='message'>Your Message</label>
<textarea class="required" rows="5" cols="80" id="message" name="message"></textarea>
</p>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="--- MY SITE KEY HERE ---"></div>
<input class="button" type="submit" value="Send message">
<p class='thanks' style='display: none;'>
Thanks for contacting Video Production Edinburgh,<br />we'll be in touch within 24 hours!
</p>
</form>
Live page with not-working reCAPTCHA can be found here.
This is the send.php code on the server side to handle the form submission:
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '--- MY SECRET KEY HERE ----',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
$to = "hello#videoproductionedinburgh.co.uk";
$name = $_POST['name'];
$subject = $_POST['subject'];
$body = stripslashes($_POST['message']);
$from = $_POST['email'];
$headers = "Reply-To: " . $from;
$error_messages = array();
if( strlen($name) < 1 ) {
$error_messages[] = "Name required";
}
if( strlen($subject) < 1 ) {
// set the default subject here
$subject = "Message from Video Production Edinburgh";
}
if( strlen($body) < 1 ) {
$error_messages[] = "Message required";
}
if( strlen($from) < 1 ) {
$error_messages[] = "Email required";
}
if(sizeof($error_messages) == 0 && mail($to, $subject, $body, $headers)) {
echo("success");
} else {
foreach( $error_messages as $error_message ) {
echo "$error_message <br />";
}
}
}
?>
At the moment the form submits successfully regardless of the reCAPTCHA being ticket or not.
Any help would be much apprecaited.
Thank you,
Paolo

Related

How to connect to api using codeigniter

newbie here in Restful API. How can I connect to the API? I've tried several ways on how to connect it but nothing seems to work. I provided the restful API connection codes below but I don't know how to connect it. I have provided my codes below. Any help will be appreciated. Thank you.
Views:
<form action="<?=base_url('account/dologin');?>" method="post">
<!-- login -->
<form id="doLogin">
<div class="input-group mb-3 dropShadow" style="padding:35px 35px 5px 45px;">
<input type="text" class="signinrow" name="formUsername" placeholder="Username">
<div class="input-group-append">
<div class="input-group-text" style="background:transparent; border: none;">
<i class="fas fa-at"></i>
</div>
</div>
</div>
<div class="input-group mb-4 dropShadow" style="padding:1px 35px 25px 45px;">
<input type="password" class="signinrow" name="formPassword" placeholder="Password">
<div class="input-group-append">
<div class="input-group-text" style="background:transparent; border: none;">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="text-bold text-sm afterLoginForm text-center" >
<p class=" mb-2" style="font-size: 18px;">
<a data-toggle="modal" data-target="#recoAcc" type="button" class="dropShadow bebas" ><u>I forgot my password </u></a><br>
</p>
</div>
<br>
<br>
<div>
<button id="btnSubmit"> Sign In</button>
<img id="submit_preloader" src="<?=pubPath('/assets/imgs/order_button_preloader.gif'); ?>" alt="Processing..." style=" display:none;" id="reg_preloader2" >
</div>
</form>
Controller:
public function dologin()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
$ci =& get_instance();
$username = $ci->input->post('formUsername');
$password= $ci->input->post('formPassword');
$ipAddress =$ip;
$baseSessionID = $ip.$username;
$url = "https://blabla.com/Auth/login";
$data_array = array('username' => $username,'password' => $password,'baseSessionID' => $baseSessionID,'ipAddress' => $ipAddress);
$data = http_build_query($data_array);
$data1 = array(
'Content-Type: application/x-www-form-urlencoded',
'Auth-Key: simplerestapi',
'Client-Service: frontend-client'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $data1);
$reply=curl_exec($ch);
$decode = json_decode($reply,true);
$username1=$decode['message'];
$password1=$decode['password'];
$userfailed=$decode['mali'];
$_SESSION["username"] = $this->input->post("formUsername");
if($username1 ==='Successfully login.'||$password1 ==='Successfully login.'){ //Login success
redirect(site_url('account/dashboard'), $data);
}elseif($userfailed ==='failed username'){ //Wrong Username
echo '<script>alert("Wrong Password or Username!");</script>';
redirect(site_url(), $data);
curl_close($ch);
I use the following code which is tested with the wordpress API and codeigniter 3. You'll need to amend the $opts array.
$method would be post, get, put ...
$url the api url ...
$opts = array('https'=>array('method'=>"GET",'header'=>"Authorization: Bearer $token"));
public function CallAPI($method, $url, $opts = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($opts)
curl_setopt($curl, CURLOPT_POSTFIELDS, $opts);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($opts)
$url = sprintf("%s?%s", $url, http_build_query($opts));
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
// The following is your code but slightly amended to change the header and suggest Authorization which is commented out. I also removed some unnecessary curl. I changed your $data_array to include the header but try it in its original form as well but with content-Type as application/json.
$url = "https://blabla.com/Auth/login";
$data_array = array('username' => $username,'password' =>
$password,'baseSessionID' => $baseSessionID,'ipAddress' => $ipAddress,
'https' => array('header' => 'Content-Type: application/json','Auth-Key:
simplerestapi', 'Client-Service: frontend-client'));
$data = http_build_query($data_array);
/*
$data1 = array(
//'Content-Type: application/x-www-form-urlencoded',
'Content-Type: application/json',
'Auth-Key: simplerestapi',
//'Authorization: Basic '. base64_encode("app_key:app_secret")
'Client-Service: frontend-client'
);
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $data1);
$reply=curl_exec($ch);
if($e = curl_error($ch)){
echo $e;
}else{
echo $decode = json_decode($reply,true);
}
curl_close($ch);

Google Recatpcha v2 Invisible not working at all says missing-input-response

I have gone through various articles over Stack as well as google and done the following implementation in Codeigniter 3. My website is running over https.
Code in head
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("enquiryform").submit();
}
</script>
Code of Form
<?php
echo form_open('SubmitForm', array('id'=>'enquiryform'));
?>
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="form-group">
<textarea type="text" class="form-control" rows="5" cols="3" name="message" placeholder="Message"></textarea>
</div>
<div class="text-center contact-page-button">
<button class="g-recaptcha btn btn-danger border-0" data-sitekey="my_site_key" data-callback='onSubmit'>Submit</button>
<input type="reset" class="btn btn-danger border-0"></input>
</div>
</div>
</div>
<?php
echo form_close();
?>
Code in Controller Function
$this->load->library('curl');
if($this->input->post('g-recaptcha-response'))
{
$recaptchaResponse = trim($this->input->post('g-recaptcha-response'));
$userIp=$this->input->ip_address();
$secret='my_secret_key';
$url="https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response;=".$recaptchaResponse."&remoteip;=".$userIp;
$response = $this->curl->simple_get($url);
$status= json_decode($response, true);
//print_r($recaptchaResponse); //prints the data
//echo "<br>";
//print_r($url); //prints the data
//echo "<br>";
//print_r($status); //prints the data
//echo "<br>";
if($status['success'] == 1) {
//True - EXECUTE SOMETHING
} else {
//False - What happens when user is not verified
$data['response']="<div class='alert alert-danger'>Failed to verify that you are a Human. Please Try again.</div>";
}
I have even tried file_get_contents method but the result is same. I always get
Array ( [success] => [error-codes] => Array ( [0] => missing-input-response ) )
I have checked the site and secret keys multiple times, they are correct. I have even placed a separate div for g-recaptcha which shows checkbox version but I still get the same errror.
What is the solution?
Problem is in your server side code. You need to send POST request instead of GET.
$url="https://www.google.com/recaptcha/api/siteverify";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,"secret=".$secret."&response=".$recaptchaResponse."&remoteip=".$userIp);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

Web form - bots getting past all checks when human cant.?

I have the following code, pretty standard - but it seems that the bots get by without even entering anything into the input fields! where as a normal person cannot since it checks upon submit, so I keep just getting empty emails.
Here is my code, if anyone has any ideas:
the javascript:
$('form.ajax').on('submit', function () {
if($(".field-b").val()) {
return false;
}
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
for(var property in data) {
if(data.hasOwnProperty(property)) {
if(data[property] == "") {
$('[name="' + property + '"]').parent().addClass("error");
return false;
}
}
}
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$(".info,.ajax").hide();
$(".success-send").fadeIn(300);
return false;
}
});
return false;
});
The HTML:
<form class="ajax" action="../email.php" method="post"autocomplete="off">
<div class="form-field">
<input name="form_name" type="text" class="form-field-name">
<label>Your Name</label>
<div class="field-icon-name"></div>
</div>
<div class="form-field">
<input name="form_business" type="text" class="form-field-business">
<label>Business</label>
<div class="field-icon-business"></div>
</div>
<div class="form-field">
<input name="form_email" type="email" class="form-field-email">
<label>Email Address</label>
<div class="field-icon-email"></div>
</div>
<div class="form-field">
<input name="form_phone" type="text" class="form-field-phone">
<label>Phone #</label>
<div class="field-icon-phone"></div>
</div>
<div class="form-field special">
<input name="form_b" type="text" class="form-field-b">
<label>question</label>
</div>
<div class="form-field">
<textarea name="form_message"></textarea>
<label>Message</label>
<div class="field-icon-message"></div>
</div>
<button type="submit">Send Message</button>
</form>
And finally the PHP.
<?php
session_start();
$to = "myemail#domain.com";
$name = $_POST['form_name'];
$phone = $_POST['form_phone'];
$email = $_POST['form_email'];
$business = $_POST['form_business'];
$email = $_POST['form_email'];
$subject = 'Contact Form mattscorner';
$message = 'Name:'.$name.'\n Email + phone:'.$email.", ".$phone."\n Business: ".$business."\n\n".$message;
$headers = "From: $email\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
if (mail($to, $subject, $message, $headers)) echo "mail sent"; else echo "mail NOT sent";
?>
It's pretty standard code I think, but I just cant seem to get the bots to even get blocked by the field requirements.
I literally get emails that are just:
Name:\n Email + phone:, Business:
There's a fundamental misunderstanding here. Bots don't run JavaScript, so none of that matters, and you're not doing the same validations on the server side, so they have no trouble getting by. Implement your validations in PHP too.
Also, you really need to do more validation for security anyway - your script is open to all kinds of vulnerabilities, and you're building malformed, non-compliant messages.
I suggest you use an email library such as PHPMailer, which you tagged this question with.

openshift form sendgrid ajax form html5 PHP BootStrap

I am trying to use an HTML form on openshift. The form controlled by Ajax. I can successfully send from OpenShift using a seperate page for the form, but I would like to use the BootStrap form. Bootstrap template is freelancer at Start BootStrap
I tried replacing the sendgrid code where the send php command was and moved return true to the end of the file.
working now-I must have had something wrong in my configuration. leaving here in case someone else wants to get a form working with openshift and sendgrid.
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
// Create the email and send the message
$to = 'xxxx'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
//mail($to,$email_subject,$email_body,$headers);
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here
// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['phone'];
$message = $_POST['message'];
// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "xxxxx", // set TO address to have the contact form's email content sent to
'subject' => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
'html' => "<html><head><title> Contact Form</title><body>
Name: $name\n<br>
Email: $email\n<br>
Subject: $subject\n<br>
Message: $message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $name\n
Email: $email\n
Subject: $subject\n
$message",
'from' => "xxxxxx", // set from address here, it can really be anything
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
return true;
?>
contact_me php from bootstrap theme
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'yourname#yourdomain.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
The working mailer.php
<?php
// use actual sendgrid username and password in this section
$url = 'https://api.sendgrid.com/';
$user = 'xxxxx'; // place SG username here
$pass = 'xxxxx'; // place SG password here
// grabs HTML form's post data; if you customize the form.html parameters then you will need to reference their new new names here
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// note the above parameters now referenced in the 'subject', 'html', and 'text' sections
// make the to email be your own address or where ever you would like the contact form info sent
$params = array(
'api_user' => "$user",
'api_key' => "$pass",
'to' => "xxxxx", // set TO address to have the contact form's email content sent to
'subject' => "Contact Form Submission", // Either give a subject for each submission, or set to $subject
'html' => "<html><head><title> Contact Form</title><body>
Name: $name\n<br>
Email: $email\n<br>
Subject: $subject\n<br>
Message: $message <body></title></head></html>", // Set HTML here. Will still need to make sure to reference post data names
'text' => "
Name: $name\n
Email: $email\n
Subject: $subject\n
$message",
'from' => "xxxxxxxx", // set from address here, it can really be anything
);
$request = $url.'api/mail.send.json';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// Redirect to thank you page upon successfull completion, will want to build one if you don't alreday have one available
header('Location: thanks.html'); // feel free to use whatever title you wish for thank you landing page, but will need to reference that file name in place of the present 'thanks.html'
exit();
// print everything out
print_r($response);
?>
the ajax file from the bootstrap template
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
// $('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
The bootstrap index.html form
<!-- Contact Section -->
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Me</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<!-- To configure the contact form email address, go to mail/contact_me.php and update the email address in the PHP file on line 19. -->
<!-- The form should work on most web servers, but if the form is not working you may need to configure your web server differently. -->
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Pardon me. The script works as is! I am not sure why it was not working, but I must have somehow corrupted my installation. I am leaving this up in case someone else wants to get emails working with openshift.

Send/Include 'name' field to Mailchimp using API with AJAX

I need to know how to send the 'name' field to Mailchimp so that it shows the 'name' the user submitted under the name column on the 'subscribers' page in Mailchimp.
The form looks like this:
<div id="email">
<form action="subscribe.php" id="invite" method="POST">
<input type="text" placeholder="Enter your name.." name="name" id="name" class="name" data-validate="validate(name)"/>
<input type="email" placeholder="and your email address.." name="email" id="MCE-email" class="email" data-validate="validate(required, email)"/>
<p>If you agree with the Terms and Privacy, please press the submit button below.</p>
<div class="clear"><input type="submit" value="Submit" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
<div id="clear"></div>
<div id="result"></div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#invite').ketchup().submit(function() {
if ($(this).ketchup('isValid')) {
var action = $(this).attr('action');
$.ajax({
url: action,
type: 'POST',
data: {
email: $('#MCE-email').val()
},
success: function(data){
$('#result').html(data).css('color', '#a1a1a1', 'padding', '10px 0px 0px 0px');
},
error: function() {
$('#result').html('Sorry, an error occurred.').css('color', 'white');
}
});
}
return false;
});
});
v</script>
The subscribe.php script looks like this :
<?php
$apiKey = 'MYAPIKEY';
$listId = 'MYLISTID';
$double_optin=false;
$send_welcome=false;
$email_type = 'html';
$email = $_POST['email'];
$name = $_POST['name'];
//replace us2 with your actual datacenter
$submit_url = "http://us5.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thank you for your email. We'll keep you up to date..";
}
?>
The field tag of the 'name' field on my form in Mailchimp is 'NAME'
I hope this is all the information you need and it makes sense..
Thank you greatly.
Going off of the Mailchimp listSubscribe function documentation found here:
http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
You just need to create a merge_vars array that will hold any additional fields associated with the subscribing email. For example:
$merge_vars = array('FNAME'=>'first name', 'LNAME'=>'last name');
And then just pass that array in your $data.

Resources