openshift form sendgrid ajax form html5 PHP BootStrap - ajax

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.

Related

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

How to fix AJAX modal form in Laravel 5.3

I've upgraded my app from Laravel 4.2 to Laravel 5.3. On an index page listing citations, I have an AJAX modal form to edit or view the login credentials for the citation. This was working fine in Laravel 4.2, but I cannot for the life of me get it to work in 5.3. After about 5 hours Googling and trying different things, I thought I would post it here so that someone way more experienced than me can point me in the right direction.
Here's the link on the index page:
<a style="cursor: pointer; " title= "Login Credentials" data-loopback="cit-pg-1" data-citationid="1079" class="getCitationdetails"><span class="glyphicon glyphicon-lock " title="Login Credentials"></span></a>
And here's the JavaScript:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error:function(){
alert('Error');
}
})
})
Here's my route:
Route::match(['get', 'post'], '/citation-password', 'CitationsController#citationpassword');
And here's the Controller method that generates the form on get and saves the data on post:
public function citationpassword()
{
if (Request::ajax()) {
$data = Request::all();
if (!$data['citationid']) {
return redirect('/citations')
->with('flash-danger', 'Missing citation id for Login credentials form!!');
}
// Save loopback variable if we have it in order to return user to the page where they came from; default return location is citations
$loopback = 'citations';
if (array_key_exists("loopback", $data)) {
$loopback = $data['loopback'];
}
$getcitationdetails = Citation::where('id', $data['citationid'])->select('id', 'site_id', 'username', 'password', 'login_email', 'login_notes')->first();
$getcitationdetails = json_decode(json_encode($getcitationdetails), true);
$getsitedetails = Site::where('id', $getcitationdetails['site_id'])->select(
'id',
'directory_username',
'directory_password',
'security_questions',
'email_account',
'email_account_password',
'email_account_name',
'google_user',
'google_pwd',
'name_of_google_account'
)->first();
$getsitedetails = json_decode(json_encode($getsitedetails), true);
$response ="";
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
if (!empty($getsitedetails['directory_username'])) {
$response .= '<div class="form-group">
<label for="recipient-name" class="col-form-label">Default login credentials for this site:</label>
<p>Username: '.$getsitedetails['directory_username'].'
<br />Password: '.$getsitedetails['directory_password'].'
<br />Email account: '.$getsitedetails['email_account'].'
<br />Email password: '.$getsitedetails['email_account_password'].'
<br />Name on email account: '.$getsitedetails['email_account_name'].'
<br />Default security questions: '.$getsitedetails['security_questions'].'</p>
<p>Gmail account: '.$getsitedetails['google_user'].'
<br />Gmail password: '.$getsitedetails['google_pwd'].'
<br />Name on Gmail account: '.$getsitedetails['name_of_google_account'].'</p>
</div>';
}
$response .= '
<input type="hidden" name="_token" value="'.csrf_token() .'" />
<input type="hidden" name="citation_id" value="'.$data['citationid'].'" />
<input type="hidden" name="loopback" value="'.$loopback.'" />
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" class="form-control" name="username" value="'.$getcitationdetails['username'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="text" class="form-control" name="password" value="'.$getcitationdetails['password'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login email used:</label>
<input type="text" class="form-control" name="login_email" value="'.$getcitationdetails['login_email'].'" autocomplete="off">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Login notes:</label>
<textarea class="form-control" style="height:130px;" name="login_notes">'.$getcitationdetails['login_notes'].'</textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="success">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</form>';
return $response;
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
In an effort to isolate the error, I even simplified the form in the controller like this:
public function citationpassword()
{
if (Request::ajax()) {
return '<p>This is the modal form!</p>';
} else {
// The popup modal has posted back here; process the data
$data = Request::all();
// Handle & translate loopback; returning user to the page where they came from
$loopback = 'citations';
if ($data['loopback']) {
$loopback = $data['loopback'];
// Translate pages it came from
$trackLoopback = new trackLoopback();
$loopback = $trackLoopback->translate($loopback);
}
$updatecitation = Citation::find($data['citation_id']);
$updatecitation->username = $data['username'];
$updatecitation->password = $data['password'];
$updatecitation->save();
return redirect($loopback)
->with('flash-success', 'Login credentials have been updated successfully!');
}
}
and also simplified the route to this:
Route::get('/citation-password', 'CitationsController#citationpassword');
but all I get when I click the link is a popup notice, "Error."
I'm not experienced with AJAX. How do I get the form to display in Laravel 5.3?
And/or, how can I change the JavaScript function so that it shows the actual error instead of the "Error" notice? (I tried a number of methods I found on StackOverflow to display errors but all of them resulted in NO error notice; just a blank page. And, I've not been successful at getting my Firefox debugger to show the errors either.)
Thanks!
The correct way to debug the JavaScript is to post the errors this way:
<script type="text/javascript">
$(document).on('click','.getCitationdetails',function(){
var citationid = $(this).data('citationid');
var loopback = $(this).data('loopback');
$.ajax({
url : '/citation-password',
type:'post',
data : {citationid :citationid, loopback :loopback},
success:function(resp){
$('#AppendLoginDetails').html(resp);
$('#LoginCredentialsModal').modal('show');
$('.loadingDiv').hide();
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
})
})
Once you do so, you will see that the error has to do with missing CsrfToken for the form. [The actual error message is from the Laravel framework: Illuminate\Session\TokenMismatchException: in file /home/reviewsites/moxy53/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php on line 6] Since both the get and post verbs use the same route, Laravel is requiring the CsrfToken before the form with the Csrf field gets generated.
It is possible (but NOT recommended!) to exclude this route from CSRF protection by editing App\Http\Middleware\VerifyCsrfToken.php with the following exception:
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'/citation-password',
];
However, a much better approach is to add the token. It is correct that since you are using a post method to send the data values to the controller, you cannot use the controller to generate the token field in the form. Hence, the solution is to take the html out of the controller and put it in the blade. These lines:
$response .= '<form action="'.url('/citation-password').'" method="post">
<div class="modal-body">';
...
</div>
</form>';
should not be in the $response generated by the controller, but should instead be in the modal div in the blade itself. THEN, you can add the CSRF field in the blade thus:
<form action="{{url('/citation-password')}}" method="post">
{{ csrf_field() }}
<div class="modal-body" id="AppendLoginDetails">
</div>
</form>

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.

Weird behaviour of CI after a redirect()

I have a strange bug during the password recovery process.
When a user loses his pwd, the app send an email with a token inside the recovery link ( http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 for exemple ) This token is an unique key inside the user table.
In the routes.php, i have :
$route['reset-password/(:any)'] = "/user/reset_password_form/$1";// new password form
$route['reset-password'] = "/register/reset_password"; //simple email form
then, reset_password_form generates a form with the token as hidden input :
public function reset_password_form($hash = NULL) { //create form to change password, with user validation hash inside
$user_id = $this->user_model->get_id_by_confirmation_code(strip_tags($hash));
if (isset($user_id)) {
$this->data['validation_code'] = $hash;
$this->data['title'] = $this->lang->line('user_title_password_edit', FALSE);
$this->template->load('default', 'register/reset_password_form', $this->data);
}
else{
$this->session->set_flashdata('error', $this->lang->line('user_error_reset_password', FALSE));
redirect('reset-password');
}
the view:
<?php $attributes = array('class' => '');
echo form_open('user/edit_password', $attributes) ?>
<input type="hidden" id="validate" name="validate" value="<?=$validation_code?>">
<div class="form-group">
<input type="password" id="password" name="password" placeholder="Password" class="form-control" value="<?php echo set_value('password'); ?>">
</div>
<div class="form-group">
<input type="password" id="password_confirm" name="password_confirm" placeholder="Password confirmation" class="form-control">
</div>
<button type="submit" name="submit" class="btn btn-success">Change password</button>
</form>
Finally, the user/edit_password function changes the user password with a new one.
public function edit_password() { //get new password and change it
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
$this->form_validation->set_rules('password_confirm', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('validate', 'Validate', 'trim|alpha_numeric|required');
if ($this->form_validation->run() === false) {
//STRANGE BUG
$URL = '/reset-password/'.$this->input->post('validate');
$this->session->set_flashdata('error', validation_errors());
redirect($URL);
}
else {
//change pssword
}
}
The bug happen when the form validation fail : i'm suposed to be redirected to the previous form ( /reset-password/hash) with a flashdata error message, but the error message dont display.
Much more weird : even if i'm on the right form ( but without error message) if i decides to click on another menu item (for exemple /home) , it immediately displays the /reset-password form ( /register/reset_password in the routes) with the error message i was supposed to get previously.
As if the full php instruction was kept in stamp and launched after whatever action.
PS : as edit_password() and reset_password_form() are in the same controller, i could have used $this->reset_password_form($hash) instead of redirect() but it has exactly the same effect !
ps2: here is the register/reset_password:
public function reset_password() {
//display forgotten password form page
$this->data['title'] = 'Forgotten password';
$this->template->load('default', 'register/reset_password', $this->data);
}
you recovery link http://localhost/reset-password/f38fd00aa975b28c70f54d948d20de40 is not finding controller. CI is looking for your token number as controller

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