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
}
?>
Related
How can I get or set the csrf_token with symfony?
here my code and I don't know how can I do with csrf_token,
$username = $request->request->get('username');
$password = $request->request->get('password');
if($request->isMethod('POST')){
$headers = array('Accept' => 'application/json');
$query = array('email' => $username, 'mdp' => $password);
$url = ' /**/ ';
$body = Unirest\Request\Body::json($query);
$response = Unirest\Request::post('$url',$headers,$body);
return new Response(json_encode($response));
}
return $this->render('AppBundle:Default:index.html.twig');
Thanks!
Symfony doesn't provide a CSRF token to every POST request by default. My recommendation would be to use Symfony Forms that give you CSRF protection out of the box. This will also make your life easier when handling form submission, adding validation rules, rendering the form, and much more.
Bartosz answer is a possibility. But if you don't want to use a Symfony form you can do in your twig template:
<input type="hidden" name="_csrf_token" value="{{ csrf_token('my_form') }}" />
In your controller:
$csrfTtoken = $request->request->get('_csrf_token');
if ($this->isCsrfTokenValid('my_form', $csrfTtoken)) {
// csrf token is valid!
}
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);
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
How do I send a notifiaction email when someone leave a comment in Facebook comments plugin.
I have this script but any time someone comes to my page I get an email.
I only want to get an email when a new user comments on the page
<script> window.fbAsyncInit = function() {
FB.init({
appId : 'appid', // App ID
channelUrl : '//http://www.corkdiscos.com/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.subscribe('comment.create', function(response){
<?php
$to = 'info#a2bdjs.com';
$subject = 'Comment Posted on Testimonial Page';
$message = 'Comment Posted on Testimonial Page';
$headers = 'From: info#a2bdjs.com' . "\r\n" .
'Reply-To: info#a2bdjs.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
You would have to make an ajax call in the following manner.
/* Get FB comment notification */
<script>
$(window).load(function(){
FB.Event.subscribe('comment.create', function(response) {
var data = {
action: 'fb_comment',
url: response
};
$.post( '`URL TO THE PHP FILE CONTAINING THE MAIL CODE`', data );
});
});
</script>
And then put the following in the above specified php file.
<?php
if ( isset( $_POST['url'] ) ) {
$to = 'info#a2bdjs.com';
$subject = 'Comment Posted on Testimonial Page';
$message = 'Comment Posted on Testimonial Page';
$headers = 'From: info#a2bdjs.com' . "\r\n" . 'Reply-To: info#a2bdjs.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
?>
You could run a few more checks to be on the safer side.
You have something weird going on there. You are placing server-side code (PHP) inside client-side code(Javascript) . The PHP code will be executed on your server, so you'll have to place that code in a separate file and make an AJAX call (with JavaScript), to that file, which will execute the PHP code and send the mail.
Get rid of that PHP code inside the FB.Subscribe function, put this instead :
FB.subscribe('comment.create', function(response){
if(typeof console != 'undefined') {
console.log(response);
}
});
Then open up the console (F12 in Chrome for the developers tools, or with firebug on firefox).
Take a look at the response variable and you'll be able to see what type of event has happened.
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.