Contact form Laravel 4 - forms

Im a noob with Laravel 4 and the contact form things is giving me some trouble to make it work.
Found few things, all using controllers but I just need it in the route.
How to do the route for a simple contact form (name,email and message) to send the datas to an admin email box?
Cheers

Here's a quick and dirty way to send e-mails using just your routes:
Create your routes
Route::get('contact', function() {
return View::make('contact');
});
Route::post('contact', function() {
$fromEmail = Input::get('email');
$fromName = Input::get('name');
$subject = Input::get('subject');
$data = Input::get('message');
$toEmail = 'manager#company.com';
$toName = 'Company Manager';
Mail::send('emails.contact', $data, function($message) use ($toEmail, $toName, $fromEmail, $fromName, $subject)
{
$message->to($toEmail, $toName)
$message->from($fromEmail, $fromName);
$message->subject($subject);
});
});
Create a app/views/contact.php
<html>
<body>
<form action="/contact" method="POST">
Your form
</form>
</body>
</html>
Create app/views/emails/contact.php
<html>
<body>
Message: {{$data}}
</body>
</html>
And you need to configure
app/config/mail.php

Related

invisible reCAPTCHA javascript

I have the invisible reCAPTCHA set up, but it doesn't seem to want to call my callback function. My form looks like:
<form id='ContactAgentForm' name='ContactAgentForm' class='custom-form-widget-form standard_form' action='contact_agent' listing_id=1233445>
...
<div class='field captcha-field recaptcha_field' >
<div id='g-recaptcha-div' class="g-recaptcha" ></div>
</div>
...
<div class="field button-field">
<button class="button button-primary"><span>Send</span></button>
<a class="button button-cancel btn-close" href="#cancel"><span>Cancel</span></a>
</div>
</form>
In the javascript, I want to handle the fact that there might be multiple forms on the page, so I create a list of all the forms. For each form, I attach/render the reCAPTCHA logic, attaching my callback with the form passed as a parameter:
<script>
var $form_list = jQuery("form.custom-form-widget-form");
var onFormPageSubmit = function(token, $form ) {
console.log("Got here! ", token );
var field = $form.find('.g-recaptcha-response')[0];
field.value = token;
$form[0].submit();
};
var onloadCallback = function() {
$form_list.each( function() {
var $form = jQuery(this);
var $recaptcha = $form.find( ".g-recaptcha" );
if ( $recaptcha.length )
{
var recaptchaId = grecaptcha.render($recaptcha[0], {
'callback': function (token) { onFormPageSubmit(token, $form); },
'sitekey': "{$captcha_config.invisible_captcha_site_key}",
'size': 'invisible',
'badge': 'inline'
});
$form.data("recaptchaid", recaptchaId);
}
});
};
</script>
And just below that, I load the recaptcha/api.js file:
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback"></script>
With some judicial 'console.log' statements, we get through all of the code EXCEPT for the callback (onFormPageSubmit). The "protected by reCAPTCHA" logo is there, but it seems that the form is just submitted, ignoring the reCAPTCHA call altogether.
All help appreciated.
Somewhere along the line, the validation function for the form was lost (it's in another file). The validation function was attached to the button, and it executed something like this:
$submit_button.on( 'click', function( event ) {
event.preventDefault();
// get the recaptchaid from form data
var $recaptcha_id = $form.data( "recaptchaid" );
if ( $recaptcha_id != undefined )
{
grecaptcha.execute($recaptcha_id);
}
} );
The "grecaptcha.execute" is the important thing - this is what triggers the actual reCAPTCHA call.

how to integrate the mailchimp with core php

I need to integrate the mail chimp api with core php I tried more type of codes but not working. Finally, I found the below code. I have created an api key with mailchimp, likewise campaigns, template and list in the mailchimp.
<script src="jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#subscribe').submit(function() {
if (!valid_email_address($("#email").val()))
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
else
{
$(".message").html("<span style='color:green;'>Adding your email address...</span>");
$.ajax({
url: 'subscribe.php',
data: $('#subscribe').serialize(),
type: 'POST',
success: function(msg) {
if(msg=="success")
{
$("#email").val("");
$(".message").html('<span style="color:green;">You have successfully subscribed to our mailing list.</span>');
}
else
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
}
});
}
return false;
});
});
function valid_email_address(email)
{
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
}
</script>
<?php
$api_key = "key";
$list_id = "id";
require('inc/MAPI.class.php');
$Mailchimp = #new Mailchimp( $api_key );
echo bool($Mailchimp);
//$Mailchimp_Lists = #new Mailchimp_Lists( $Mailchimp );
//$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['email']) ) );
if ( ! empty( $subscriber['leid'] ) ) {
echo "success";
}
else
{
echo "fail";
}
?>
<div class="message"></div>
<form role="form" method="post" id="subscribe">
<input type="email" id="email" name="email" placeholder="you#yourself.com" value="">
<button type="submit">SUBSCRIBE</button>
</form>
This is my code, but it's not returning, errors only. Please help me.

How to run a PHP script in the background after a form is submitted and redirect it to another php page?

I am using the post method in a php script as:
<form method="post" enctype="multipart/form-data" action="file1.php">
after submitting the form it runs the file1.php which takes 20-30 minutes to finish and the page hangs over here. I want to redirect this page to another page file2.php and the file1.php should be run in background without exiting it.
Please suggest me any way to redirect it. I have tried using header('Location: file2.php'); in file1.php but it redirects only after completing the file1.php.
form.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<style>
#console {
width: 100%;
height: 500px;
overflow: auto;
border: 1px solid #4E4E4E;
}
</style>
</head>
<body>
<form id="myForm">
FirstName:
<input type="text" name="firstName">
<br> Second Name:
<input type="text" name="lastName">
<br> Phone No.:
<input type="text" name="phoneNumber">
<br>
</form>
<button id="submitMyForm">submit the form!</button>
<br>
<!-- JUST SOME FEEDBACK TO LET US KNOW WHAT IS SENT -->
<h1>SENT: <span></span></h1>
<div id="console"></div>
<script>
// on click of the button submit form and run php on process.php
$("#submitMyForm").on("click", function() {
// get data from the form and serialize it.
var dataFromForm = $('#myForm').serialize();
// -------------------------------------------
// for your information:
// this is the format of what we are sending over
// -------------------------------------------
$("h1 span").append(dataFromForm + "<br>");
// -------------------------------------------
$.ajax({
type: "POST",
data: dataFromForm,
url: "process.php",
success: function(data) {
// -------------------------------------------
// for your information:
// just show what we got back from the server
// -------------------------------------------
$("#console").append("SUCCESS: " + data + "<br>");
// -------------------------------------------
},
error: function(data) {
// if it does not work do whatever you want.
console.log("ERROR");
console.log(data);
}
});
// ------------------------------------------------
// ADD THIS TO REDIRECT TO WHEREVER
window.location.replace("http://stackoverflow.com");
// ------------------------------------------------
});
</script>
</body>
</html>
process.php
<?php
// ------------------------------------------------------------------------
// Do whatever you want here for the script.
// It will start running and allow you to continue doing whatever on the form page
// you dont need to echo out anything. It is just to show its running the script
// ------------------------------------------------------------------------
echo "
STARTING SCRIPT: USING VARIABLES SENT FORM DATA<br>
first name: " . $_POST['firstName'] . " <br>
last name: " . $_POST['lastName'] . " <br>
phone number: " . $_POST['phoneNumber'] . " <br>
";
?>
I used this helper static method with success for many years.
<?php
namespace Libraries;
class Helper
{
public static function redirect($location = null, $ignoreAbort = true)
{
header('Connection: close');
ob_start();
header('Content-Length: 0');
header('Location: ' . $location);
ob_end_flush();
flush();
if ($ignoreAbort) {
ignore_user_abort(true);
}
}
}
This is how to use it.
<?php
namespace Controllers;
class OrderController{
public function orderCompleted()
{
// If you need to send a message after redirect.
$_SESSION["order_completed"] = "Order completed";
// don't forget to unset the session after the message is seen.
// Redirect should be put before the long duration script
Helper::redirect('https://www.your-url.com/page);
// Run in background
// 1. Send emails
// 2. Generate PDFs
// 3. etc...
}
}
Note:
You also need to check the PHP settings (php.ini)
Some installs do not have output_buffering on, some have 4096, some default to Off
# output_buffering = Off
# Use
output_buffering = 4096
# Or unlimited, but use with caution
output_buffering = On
You can try the curl if you want to execute the php code in background.
A simple example with parameters:
<?php
$url = 'http://yoursite.com/yourbackground-code.php';
$fields = array(
'param1' => "data",
'param2' => "data",
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//you can var_dump the result after is executed
var_dump($result);

display thank you message when contact form submitted

Ok, so I've looked on the forum and see similar questions to this, but i'm still not getting anywhere with the code i've pilfered from various pages.
I'm using bootstrap css to display a contact form, usual fields, name email, message etc. The action="process.php" which is where I add the user into a mysql database and then email me a confirmation that someone has submitted the form. So all is well on that front, just that I want to display a simple "thank you" message once the form has been submitted, but not by redirecting to another page.
I have the following for a message:
<!-- thank you message -->
<div id="thanks" class="alert alert-success fade">
<button href="#" type="button" class="close">×</button>
<h4>Got it!</h4>
<p>Thanks. I've received your message, I'll be in touch within 24 hours. Promise.</p>
</div>
and then use this js to add the "in" to display it once submitted:
$('#send_button').click(function () {
$('#thanks').addClass('in');
});
$('.close').click(function () {
$(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
});
I briefly see the thank you alert message, but then I get redirected to "process.php" and this doesnt display anything as theres no html within, just the mysql stuff and php mailer.
Another point to note, whether this is of interest, I load the contact form initially by ajax so the url is like wdr/index.php#contact
Can someone help me finish the code. I'm sure its something simple I'm missing to make this work as it should.
Any help appreciated.
Col
Using Ajax makes it easy. here is what I use for simple sends:
The js:
$('#form_id').on('submit', function(e) {
e.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader', form).html('<img src="../img/forms/loader.gif" /> Please Wait...');
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
});
The process.php:
<?php
/* Configuration */
$subject = 'Submission received'; // Set email subject line here
$mailto = 'your email address'; // Email address to send form submission to
/* END Configuration */
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$companyName = $_POST['companyName'];
$phone = $_POST['phone'];
$callTime = $_POST['callTime'];
$timestamp = date("F jS Y, h:iA.", time());
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $firstName $lastName<br>
<b>Email</b>: $email<br>
<b>Company name</b>: $companyName<br>
<b>Phone number</b>: $phone (Please call in the <b>$callTime</b>)</p>
<p>This form was submitted on <b>$timestamp</b></p>
";
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span12\">
<h3>Submission successful</h3>
<p>Thank you for taking the time to contact Pacific One Lending. A representative will be in contact with you shortly. If you need immediate assistance or would like to speak to someone now, please feel free to contact us directly at <strong>(619) 890-3605</strong>.</p>
</div>
</div>
";
$headers = "From: $firstName $lastName <$email> \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $message, $headers)) {
echo "$success"; // success
} else {
echo 'Form submission failed. Please try again...'; // failure
}
?>

How to use Facebook FBJS Feed Forms

I'm trying to call a Feed Form in my Facebook application and I'm not sure how to do so. I'm not familiar with the FBJS and its API. Specifically I need the following dialogue to show up: http://wiki.developers.facebook.com/index.php/Feed_Forms
Here's what I got for now:
<script type="text/javascript">
var attachment = <?php echo json_encode($attachment); ?>;
return attachment;
Facebook.streamPublish(<?php echo $message; ?>, attachment, null, <?php echo $user; ?>);
</script>
Is there anything else I need to do in order to properly call a Feed form? A code example would help me a lot if anyone is willing to write one up.
Here's an example I use from a Facebook Connect site that I operate:
var message = 'This is my message!';
var attachment = {
'name':'Page name',
'href':'http://mysite.com',
'caption':'Some kind of caption';
};
attachment.media = [{'type':'image','src':'http://mysite.com/images/lolcat.jpg','href':'http://mysite.com'}];
var action_links = [{'text':'Action Link!','href':'http://mysite.com'}];
FB.Connect.streamPublish(message, attachment, action_links);
The FB.Connect methods are almost identical to the normal JS methods, so something similar should be working for you.
I would point out that you have <?php echo $message; ?> as the first parameter to your Facebook.streamPublish() call. Assuming $message is a text string, then you need to wrap that output in quotes in order for it to be valid Javascript. As well, the return attachment; line doesn't make much sense to me. Why is there a return statement there? I would change your code to this:
<script type="text/javascript">
var attachment = <?php echo json_encode($attachment); ?>;
Facebook.streamPublish('<?php echo addslashes($message); ?>', attachment, null, <?php echo $user; ?>);
</script>
For FBML canvas pages, all you need to do is execute the command as follows:
<script type="text/javascript">
var attachment = <?php echo json_encode($attachment); ?>;
Facebook.streamPublish('', attachment, null);
</script>
That should easily bring up the Feed Form.