Execute jQuery script after submitting a form - php

I want to execute a jQuery script after submitting a form. The jQuery script it's only a line that will fade In a hidden that will show if the e-mail have been sent or not sent.
The PHP code is at the top of the file and I don't know if staying the PHP code at the top is the problem but I tried moving de PHP above the jquery script but it doesn't work.
EDIT:
Now I have that code in my index.php
$(document).ready(function) {
$('form').submit(function) {
$.ajax({
url: "mail.php",
type: "POST",
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(response) {
$('#result').html(response);
}
});
return false;
});
});
In mail.php I have that other code
$name = $_POST['name'];
$mail = $_POST['email'];
$msg = $_POST['msg'];
if(mail('test#test.com', $name, $msg)) {
echo 'Pass!';
} else {
echo 'Fail!';
}
When I executed it nothing happens and the URL shows the data that I wrote in the inputs but any message appears.

Here's a simple example for processing a form with AJAX. Notice the IDs: #emailForm is the ID of the form, and #out is the ID of some HTML element (such as a div or p) where you want to display the result. The function email.php is your server side script to send the email and return the result.
$(document).ready(function() {
$('#emailForm').submit(function(){
$.ajax({
url: "email.php",
type: 'POST',
data: {
name: $('input[name="name"]').val(),
email: $('input[name="email"]').val(),
msg: $('input[name="msg"]').val()
},
cache: false,
success: function(responseText){
$('#out').html(responseText);
}
});
return false;
});
});
On the server side, email.php (or whatever you want to call it) processes the data and sends the email. The data can be retrieved from the $_POST array. After sending or attempting to send the email, email.php can simply echo the result to be inserted in the HTML element with the id of "out."
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['msg'];
//PUT CODE HERE FOR SENDING EMAIL
if ($success){
echo "Email sent with success!";
} else {
echo "Unable to send your email at this time. Please try again later.";
}
The output should appear in the HTML element:
<div id="out">Email sent with success!</div>

you can use onSubmit attribute in form tag
e.g.
<form name="anything" id="anything" onSubmit="functionname();" >
or the other option is onClick of Submit button
<input type="submit" onClick="functionname();" value="SUBMIT FORM" />
I personally preffer 1st method

Related

PHP echo statement not working

I have following form processing php script.
<?php
$G['hotel_email']="xxxx#xxxx.com";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";
# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';
# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
$js = '';
# ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
if (!empty($_POST['title'])) { exit; }
# FORM MAIL TO SENT
unset($_POST['title']);
unset($_POST['submit']);
$message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
foreach ($_POST as $field => $value) {
$message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
}
$message .= "\n\n\n";
mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
echo "success";
}
?>
The form is being submitted using following JavaScript
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("#ba-form-contact form").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
First_Name: "required",
Surname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
}
},
submitHandler: function() {
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
return false;
}
});
});
</script>
The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?
As per your ajax request, you are not using success method here in ajax request, you need to add success method as:
jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",
success: function(response) {
alert(response); //this will return the response
},
beforeSend: function()
{
// loading if you need before ajax success
}
});
return false;
Here success: function(response) { will return the success message.
You do not know that it is the echo that does not work.
What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
The above does not do anything with the output, so logically nothing happens.
Try this:
jQuery.post({
'<?=$_SERVER['REQUEST_URI']?>',
jQuery("#ba-form-contact form").serialize()
}).done(function(retval) {
// Debug (better use console.log actually)
alert(JSON.stringify(retval));
// Do what you want with retval.message (check retval.status also)
alert(retval.message);
});
and in the PHP, which must output nothing else, end with:
header('Content-Type: application/json');
die(json_encode(array(
'status' => 'success',
'message' => 'The mail was sent',
)));
(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).

How to send external form POST data through AJAX

I have a web form, simple HTML / PHP that works by itself but when it is passed onto the template page via the below AJAX call -- the post data is missing on submission. This HAS got to be a param I'm missing below.
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
The request is sent. And upon submission I receive email, everything but the selected post data via form is sent. Below is the PHP.
<?php
$backwheel = $_POST['backwheel'];
$frontwheel = $_POST['frontwheel'];
$form_message = "backwheel:".$backwheel." frontwheel:".$frontwheel." \nMessage: ". " You just recieved a new custom order via your Customizer!"."\nFullCustomURL: ".$_SERVER['HTTP_REFERER'];
mail("email#gmail.com", "Your Website Something", $form_message, "From: Capn Ron (New Order!)" );
if (isset($_POST['submit']))
{
echo "<script>
alert('Thanks for your Order!');
window.location.href='http://www.website.com';
</script>";
}
?>
You're not missing a param. From your code, #toggle3 appears to be button since the click event is bound to it. So, if you try to serialize it, it will certainly return nothing. You have to serialize the surrounding form which is easily achieved by using jQuery's closest() function; i.e.:
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(),
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});

Send Email with PHP/AJAX From HTML Form

I want to send the information the user has filled out from an HTML form to my email address. From my understanding, this cannot be done by using only client-side coding due to the nature of how emails work, and suggested to use PHP (combined with AJAX) to handle the server-side code. I followed the guide here but I am not receiving any emails at my email address. I am testing locally on my machine (using XAMPP) before I deploy my code on my client's web space (goDaddy). I want to note that I have never used PHP before.
Javascript:
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: data,
dataType: "text"
});
PHP (email.php):
<?php
$to = "myself#hotmail.com";
$subject = "This is my email";
$message = $_REQUEST;
$send = mail($to, $subject, $message);
if(!$send){
die();
}
?>
XAMPP doesn't have an e-mail sending thing by itself as default. You may check the links below;
php mail setup in xampp
How do I enable XAMPP to locally use the php's mail() function so I can test my mail() scripts locally without having to upload to my server?
You should replace $_REQUEST with $_REQUEST["data"] or something like this, because $_REQUEST is an array.
all time the page is being refreshed. Below is my code:
HTML 5:
<form method="post" data-ajax="false">
<input type="text" name="email" placeholder="jack#example.com, jil#example.com">
<input type="submit" name="submit" value="Invite" class="submitBtn">
</form>
JS:
$('form').bind('submit',function(){
$.ajax({
type : 'POST',
url : 'data/invite.php',
data : $(this).serialize(),
cache : false,
dataType: 'text',
success : function (serverResponse) { alert('mail sent successfully.'); },
error : function (jqXHR, textStatus, errorThrown) {alert('error sending mail');}
});
})
PHP:
<?php
$to = $_POST['mail'];
$name = 'Indusnet Technologies';
$subject = 'Think Recycle';
$text = 'Welcome to our site';
$message =' You received a mail from '.$name;
$message .='Text of the message : '.$text;
if(mail($to, $subject,$message)){
echo 'mail successful send';
}
else{
echo 'there’s some errors to send the mail, verify your server options';
}
?>
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: data,
dataType: "text"
});
This Code shoud be like this
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: {"data": data},
dataType: "text"
});
and get in code either through $_POST['data'] or $_REQUEST['data']
You probably should return false to the form. Try this:
$('form').submit(function(){
$.ajax({
type : 'POST',
url : 'data/invite.php',
data : $(this).serialize(),
cache : false,
dataType: 'text',
success : function (serverResponse) { alert('mail sent successfully.'); },
error : function (jqXHR, textStatus, errorThrown) {alert('error sending mail');}
});
return false;
})

Problem with Jquery AJAX and more than 2 variables

I am trying to add a tell a friend section to a website I am making but I am having difficulty trying to send more than 2 variables through a URL with AJAX. This is the code I have at the moment:
jQuery("#tellafriendsubmit").click(function() {
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: "POST",
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name=name&email="+email,
success: function(msg){
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
});
If I remove the '&name=name' part so that I'm only sending the postname and email address, it works fine but I need to send the name as well so I can write 'Dear $name....'
How can I send the extra 3rd variable? Thanks for any help
Edit:
The part I'm using in the tellafriendprocessor page looks like this:
$email = $_POST['email'];
$post_name = $_GET['postname'];
$name = $_POST['name'];
$to = $email;
$subject = "Example - Tell a friend";
$body = "Dear $name http://www.example.co.uk/ads/$post_name";
if (mail($to, $subject, $body, $headers)) {
} else {
}
You could try sending them as part of the POST request body (using the data property) which will ensure that those values are properly encoded:
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: 'POST',
url: 'http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>',
data: { name: name, email: email },
success: function(msg) {
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
On the server side make sure you are reading them from the $_POST hash ($_POST["name"] and $_POST["email"]).
you can send your parameters to a page with AJAX by GET and POST method with this piece of code
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
Here is an example
$.ajax({
type:"GET",
cache:false,
url:"welcome.php",
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
success: function (html) {
$('#add').val('data sent sent');
$('#msg').html(html);
}
});
You will need to move name outside the string. And to add more key-value-pairs you just append them to the query string: &key=value
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name="+name+"&email="+email
Try to use object of params like this:
$.post("/tell-a-friend-processor-page/", { name: "John", email: "<?php echo $post_email; ?>", post_name: "<?php echo $post_name; ?>" },
function(data) {
alert("Data Loaded: " + data);
});

jQuery/ajax form - send to php problem

I have a nice looking slideup/slidedown jquery form on my website. It sends the data to the same file to send the email. This works fine:
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
The php at the top of test.php to send the email:
include("expander-b1.0.php");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
sendmail("admin#site.co.uk", $message, "Contact message from $name", $email);
This is getting my simple mail function from a external file. However, I would like some way to validate the form entry (including email validation), then display the error(s) in the contact dive. I am not that experienced with jQuery or ajax but an unable to get it working with using if statements in my php and echoing the variables in the "success" part of the ajax.
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
//Email Validation
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email) == false) {
alert('Invalid Email Address');
return false;
}
//Name and message VALIDATION
//-------- goes here ------------//
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
you need to use mysql_real_escape() to filter evil code in the post and you can use regular expression to check for a valid email. if you google for it you will find a lot of documentation and tutorials about that.
you can also make it easy on yourself and buy (or find a free one) a ready to use validation class -> Codecanyon validation class
and about the success part have a look at this question -> how can i create a success back function?
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
A JQuery-based validation script that works very well to validate and automatically insert error messages if a section of your code fails validation. Simply include files, add jquery (see source of examples for best methods) and add the "required" element to your class names. Should be a perfect solution to your problem....with no crazy math or individual selectors required.

Categories