AJAX form submission, solely to prevent page refresh and nothing else - javascript

I've built a simple HTML/PHP e-mail sign-up form to appear in the footer area of my website. There are only two fields: email and country.
The form works perfectly for my purposes. Data collection, validation, sanitization, error handling, clear fields, success notification, etc. -- ALL GOOD!
My final step is to implement AJAX to prevent a page refresh. This is all that is required from AJAX.
All tutorials, articles, and answers to related questions on this site I have found offer code that includes functions I've already handled with PHP.
I've gotten as far as the AJAX submission, which works. The page doesn't refresh, user input is inserted to the database, and I receive the confirmation e-mail.
I would appreciate some guidance (or a link to a tutorial) that can help me implement the PHP error logic and echo PHP success/error messages.
HTML
<form action="process_footer_form/" method="post" id="footer-form">
<ul>
<li>
<input type="email" name="email" id="email"
value="<?php if (isset($email)) {echo $email;} ?>">
</li>
<li>
<input type="text" name="country" id="country"
value="<?php if (isset($country)) {echo $country;} ?>">
</li>
<li>
<input type="submit" name="submit" id="submit">
</li>
</ul>
<?php if (isset($success_message)) {echo $success_message;} ?>
<?php if (isset($error_message)) {echo $error_message;} ?>
</form>
JQuery
$(function() {
// identify form
var form = $('#footer-form');
// create event listener
$(form).submit(function(event) {
// disable html submit button
event.preventDefault();
// serialize form data
var formData = $(form).serialize();
// submit form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// 1. echo PHP success message
// 2. fire PHP clear fields command
})
.fail(function(data) {
// 3. execute PHP error logic here
// 4. echo PHP error messages
});
});
});
PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Load PHPMailer
require 'PHPMailer/PHPMailerAutoload.php';
// Create PHPMailer session
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
// SMTP settings
$mail->isSMTP();
$mail->Host = 'smtp.xxxxxxxxxx.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->Username = 'xxxxxxxxxxxxxxxxxx';
$mail->Password = 'xxxxxxxxxxxxxxxxxx';
$mail->setFrom('xxxxxxxxxxxxxxxxxx' , 'xxxxxxxxxxxxxxxxxx');
$mail->addAddress('xxxxxxxxxxxxxxxxxx');
$mail->isHTML(true);
// Sanitize & Validate Input
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$country = trim(filter_input(INPUT_POST, 'country', FILTER_SANITIZE_SPECIAL_CHARS));
// set connection to mysql server
$connection = mysql_connect("localhost","xxxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxxxx");
// connect to database
mysql_select_db("xxxxxxxxxxxxxxxxxx", $connection);
// insert user input to table
$sql = "INSERT INTO email_subscribers (email,country) VALUES ('$email','$country')";
if (!$connection) {
$error_message = <<<ERROR
<div>ERROR. Form not sent. Please try again or contact us.</div>
ERROR;
// Send error notice to host
$mail->Subject = 'Website Error - Footer Form';
$mail->Body = ("Error Notice: A site user is having trouble on the footer form.");
$mail->send();
} else {
// run query
mysql_query($sql, $connection);
$success_message = <<<CONFIRMATION
<div>Subscription complete. Thank you!</div>
CONFIRMATION;
mysql_close($connection);
// Send confirmation notice to host.
$message = <<<HTML
<span>E-mail: {$email}</span><br>
<span>Country: {$country}</span>
HTML;
$mail->Subject = 'New E-mail Subscriber - Footer Form';
$mail->Body = $message;
$mail->send();
unset($email, $country);
}
} else {
header('Location: http://www.mywebsite.com/');
exit;
}
?>

You might try simplifying your life by using the FormData object. Then your code could look something like this. I have tested this out.
<form method="POST" id="subscription-form" enctype="multipart/form-data">
<input type="email" name="email" id="email" value="gulliver#tinyletter.com">
<input type="text" name="country" id="country" value="Lilliput">
<input type="button" value="submit" id="form-submit">
</form>
Below this you could put in a div for displaying messages:
<div id="messages"></div>
Then your jquery/javascript would look something like this:
<script>
(function(){
$("#form-submit").on("click", function(){ submitForm();});
})();
function submitForm(){
var form = document.getElementById("subscription-form");
var fd = new FormData(form);
$.ajax({
url: './PHPscript.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
$("#messages").html(data);
}
});
}
</script>
Regarding letting PHP "handle the messages" I think you're missing something about AJAX.
In your initial PHP page you are loading the html that PHP has generated and then PHPs part is finished. When you make the AJAX call you are asking the server to execute a different PHP script and then return the output of that script back to javascript.
At that point you need to put whatever message PHP has generated back into the current page, which has not and will not reload. That was the purpose of using AJAX in the first place. That is what the "messages" div is for.
As a way of completely understanding this create an extremely simple PHPscript.php file that looks like this and try it out:
<?php
print $_POST['email'] . ' ' . $_POST['country'];
?>
You will see your values returned in the current page inside that messages div.

The first request to, for example www.mysite.com/something.php will run the PHP and dump the result into the page. Ajax doesn't work this way. You send a request to your PHP file, and it sends a response that you can then inspect and do something with.
If ajax responses dumped their content into the page like an initial load, mayhem would ensue.
Try something like this:
$.ajax({
url: url,
type: type,
data: data
}).done(function (response) {
console.log(response);
});
then have a looksie in the console and see what goodness you're getting from the PHP script. Then build that .done callback up to process the results of your request and determine what to do.

Okay, first thing, var that = this is a trick when you loses context, but where you use it is not somewhere you can lose it .. so forget it :)
Then your find().each(), it's a good way of getting your values, but jquery offers a method which is $( this ).serializeArray() (it does kinda exactly what your want)
Also, you send your data with ajax, but you have no callback. Your ajax call need to have at least a function to call once everything went fine. This is done with done()
Finally, returning false does cancel the event in most cases but you will prefer preventDefault() as it disable default behavior, but still propagate event (for other handlers).
Sum it all:
$('form.ajax').submit( function(event) {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serializeArray()
}).done(function(data) {
alert("Ajax call successful");
console.log("Server answer:" + data);
});
event.preventDefault();
});
Edit: Nvm my first remark, I understood lately your that = this stuff.

Related

how to make a contact from html form and php page by ajax

I make this form to send data to a php page in another domain but always it results error. can someone explain my problem
I search in Internet many times but exactly I didnt find my answer
here is my code
html:
<form action="#" id="smail" method="post" class="form">
<input type="text" name="name" value="Your Name *">
<input type="text" name="mailadd" value="Your E-mail *">
<textarea name="message" cols="0" rows="0">Your Message *</textarea>
<input type="submit" value="send message">
</form>
js:
$('#smail').submit(function(event) {
event.preventDefault();
var mail = $("#smail input[name=name]").val();
var message = $("#smail input[name=mailadd]").val()+' '+$("#smail textarea[name=message]").val();
$.ajax({
type: "POST",
url:"http://cofeebeen.dx.am/email.php",
crossDomain: true,
data:{
"mail": mail,
"message": message,
},
dataType: "text",
error: function(){
alert("error")
}
}).success(function(result){
alert(result)
});
});
php:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
Your PHP code is not correct, we can get data at your PHP page like below.
Correct code:
$subject = $_POST["mail"];
$msg = $_POST["message"]
Incorrect code:
$subject = $_POST["name"];
$msg = $_POST["mailadd"]
I hope it will work now.
Per #mpf82's comment, if this is a cross domain request, that changes things. However, the AJAX request is currently passing 2 PHP post variables:
...
data:{
"mail": mail,
"message": message,
},
...
And you reference 3:
$_POST['name'];
$_POST['mailadd'];
$_POST['message'];
As #Reghbendra pointed out, you are referencing the incorrect variable names. Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP.
Therefore, your code would need to reference the two post variables that were passed by their proper indexes.
Result code:
<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone#example.com",$subject,$msg);
?>
You also should consider the headers for the PHP mail function to ensure that it sends properly and is handled correctly. See the documentation for the function here.

Submitting Form Details using PHP

I am fairly new to PHP. I have to send the form details to mail id. I browsed through The Internet and get the various link about the same. But I am facing the similar situation that when I am submitting my form filled with details then it is downloading the PHP file in the browser and main thing is I am not getting mail.
Here I pasting my code-
HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>AJAX Contact Form Demo</h1>
<div id="form-messages"></div>
<form id="ajax-contact" method="post" action="mailer.php">
<div class="field">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="field">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="field">
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
<script src="jquery-2.1.0.min.js"></script>
<script src="app.js"></script>
</body>
</html>
The mailer.php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
//
$recipient = "shubhamvashishtha22#gmail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
My app.js file
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
});
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// TODO
});
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
Can anyone please suggest me how I can make this problem go. I am actually just copying it than also this is happening. Please help me?
It is possible that your server doesn't have a SMTP likesendmail or postfix enabled. You can run phpinfo() and look for this directive sendmail_path and see what is set.
You say that the PHP file is downloaded through the browser. This is not supposed to happen. When the server gets a request for a PHP file, it is meant to run the PHP code and only respond with the resulting HTML page. Visitors to your web page should never see any code, only the text and tags you choose to echo, which leads me to believe that your server may not actually be running PHP at the moment.
Is your PHP installation configured correctly, and is it running? If you are not configuring your own server, does your web host of choice have PHP listed as one of the languages it supports?
Your AJAX doesn't seem to do anything other than telling the form to submit, so I don't think it's the problem, but for the sake of isolating the issue: What happens if you comment out the jQuery and AJAX script tags and just use a regular HTML form to POST to mailer.php?

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

how to send an email to admin by running a php file through jQuery

i need to get a notification email to my site admin, when one user made a request through a from. my code is as follows, to link the php file in my server which sends the mail
$("#modelform").submit(function (event) {
event.preventDefault();
$.ajax({
url: 'send_mail.php',
success: function(){
alert('php runing');
$("#sendRequest").modal("show");
$("#myModal").modal("toggle");
}
});
});
but it doesn't react! my knowledge is little low can anyone guide me to achieve this? i checked this question is this wrong the way i do or do i need to link any file other than bootstrap libraries?
You can try something like this:
The HTML:
<textarea id="contactUs"></textarea><div id="button">Send</div>
<div id="response"></div>
The jQuery:
$("#button").click(function(){ //when div id="button" is clicked
var content = $("#contactUs").val(); //get value of textarea id="contactUs"
$.post('send_mail.php',{content: content}, function(data){ //post data
$('#response').html(data); //return content of send_mail.php
});
});
Then the send_mail.php:
<?php
if(isset($_POST['content']) === true){
$content = $_POST['content']; //might wanna sanitize if you're storing into db
$to = "YourEmail#example.com"; //The email sending to
$subject = "Sent From Contact form"; //The subject of email
mail($to, $subject, $content, 'From: contact#example.com'); //PHP mail() function
echo "Sent!"; //This will go to div id="response" on success
} else {
echo "Error!"; //This will go to div id="response" on error
}
?>

validate captcha before submit

I've use captcha for form registration, within that I have validation engine for form inline validation. I'm stuck in validating the equity of captcha.
<p class="veriText">
<label>Enter the Verification Text </label> <span style="color:red;">*</span>
<input class="validate[required] text-input" type="text" name="captcha" id="captcha" class="text" value="" />
</p>
<img src="<?= get_bloginfo('template_url'); ?>/captcha_code_file.php?rand=<?php echo rand();?>" id='captchaimg'><br/>
PHP validation: (works perfectly)
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
}
But the same thing in js I have tried like
var session = <?php echo $_SESSION['code'] ?>; // this value is different
// from captcha image
Is it possible to validate captcha before submitting the form in Javascript/jQuery?
Assuming the line var session = <?php echo $_SESSION['code'] ?>; is in your html page.
When the page is generated your captcha image script is not invoked and thus $_SESSION['code'] is not initialized. The value you are getting is the code from the previous request to captcha_code_file.php. Once your page is loaded (at-least the html part) and the browser decides to call captcha_code_file.php your captcha image gets invoked and a new $_SESSION['code'] is created.
I don't recommend this, but if you want to get the current $_SESSION['code'] try to use an Ajax request to retrieve the new $_SESSION['code'] from another php file (don't call captcha_code_file.php or your session will be reset again.
Note: Never try to validate your captcha at user end. You are defeating the main purpose of captcha.
Create one ajax request for checking capcha using JavaScript, example is provided below:
var postData = $("form").serialize();
var requestUrl = '/check_capcha.php';
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: requestUrl,
success:function(data){
// success or fail message
}
});
check_capcha.php contains:
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
echo 0;
}else{
echo 1;
}
exit;
You can put the javascript code before (although session is same throughout the page).
Just try a dummy code in a plain file and check the session value
OR
You can use $.ajax() to call PHP page for captcha validation
html look like this
$rand = mt_rand(100000,999999);
<span class="captcha"><?php echo $rand; ?></span>
<input name="captcha" type="text" id="captcha-compare" />
In javascript use something like that for validation engine
$('#frm-register').submit(function() {
if( $('#captcha-compare').val() != $('.captcha').text() ) {
$('#captcha-compare').validationEngine('showPrompt', 'Invalid captcha', 'load');
return false;
}
});
and in php first take $rand in session then submitting capture the input text captcha and session
You can try the below code to validate the captcha or you can also use AJAX code to validate the values before submitting the code.
<script language="JavaScript">
var session = '<?php echo $_SESSION['code'] ?>';
if(Form.captcha.value == session)
{
return true;
}
else
{
Form.submit();
}
</script>

Categories