Php Ajax Form is not submitting - javascript

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file

Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

Related

how to use ajax to perform php background submission in html

Hi i'm trying to converting my form data to pdf like below.
HTML -> AJAX -> PHP (fpdf)
After click submit button ajax processing & pop message as "localhost say : ok"
if i not full any input name in html , ajax pop say "please fill all fields."
why ajax not able to reach php did i done any thing wrong in php, please help.
Below my code :
html code :
enter code here
<form id="form">
<div class="row">
<div class="col-md-12 form-group container"" >
<center> <b>E-FSR Reporting</b>
<p name="date" id="date"></p>
</center>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group" >
<input type="text" class="form-control" name="name" id="name" placeholder="name" >
</div>
</div>
<div class="row">
<div class="col-12 ">
<td colspan="2" align="center" >
<input type="submit" id="submit" name="submit" value=" Submit E-FSR " class="btn btn-primary rounded-0 py-2 px-4">
</td>
<span class="submitting"></span>
</div>
</div>
ajax code : script.js
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
var dataString = 'name='+ name;
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
php code : pdf.php
enter code here
<?php
if(!empty($_POST['submit']))
{
$name= $_POST['name'];
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
....
Thanks
You are sending you data in a incorrect way:
Your javascript code should be like this:
$(document).ready(function(){
$("#submit").click(function(){
var name= $("#name").val();
if(name=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "pdf.php",
data:{
name:name
},
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
Remark:in php when you fetch data from the $_POST the key should be like how you sent it from ajax.
From example in ajax you are writing
data:{
name:fname,
gender:mygender
}
Then in php it should be $_POST["name"] and $_POST["gender"].

PHPMailer Contact Form with Jquery

I created contact form using phpmailer. and, it is working and send email fine. but, It does redirect in php file & then show message for successfully.
I want to show message on same contact form html page. and, I used below ajax jquery for that. but, mail does not send. and does get below message on same form html page.
There is a problem with the document!
How can i fixed this?
JS Code:
(function ($) {
"use strict";
var form = $('#contact-form'); // contact form
var submit = $('#submit-btn'); // submit button
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'php/mail.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
submit.attr("disabled", "disabled");
var loadingText = '<span role="status" aria-hidden="true" class="spinner-border spinner-border-sm align-self-center mr-2"></span>Sending.....'; // change submit button text
if (submit.html() !== loadingText) {
submit.data('original-text', submit.html());
submit.html(loadingText);
}
},
success: function(data) {
//$('.alert-dismissible').remove();
submit.before(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html(submit.data('original-text'));// reset submit button text
submit.removeAttr("disabled", "disabled");
},
error: function(e) {
alert('error');
}
});
});
})(jQuery);
mail.php Code:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$myCompanyName = "CompanyName";
$myCompanyEmail = "noreply#CompanyName.com";
$myCompanyEmailPassword = "CompanyEmailPassword";
$myPersonalEmail = "personalEmail#gmail.com";
require './phpmailer/src/Exception.php';
require './phpmailer/src/PHPMailer.php';
require './phpmailer/src/SMTP.php';
if(isset($_POST['submit'])) {
$mail = new PHPMailer(true);
//$mail->SMTPDebug = 0;
$mail->Host = 'smtp.mboxhosting.com';
$mail->SMTPAuth = true;
$mail->Username = $myCompanyEmail;
$mail->Password = $myCompanyEmailPassword;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom($myCompanyEmail, $myCompanyName);
$mail->addAddress($myPersonalEmail);
$mail->addReplyTo($_POST['email'], $_POST['name']);
$mail->isHTML(true);
$mail->Subject = 'My Subject';
$mail->Body = $_POST['message'];
try {
$mail->send();
echo 'Your message was sent successfully!';
} catch (Exception $e) {
echo "Your message could not be sent! PHPMailer Error: {$mail->ErrorInfo}";
}
} else {
echo "There is a problem with the document!";
}
?>
Form HTML Code:
<form id="contact-form" action="php/mail.php" method="post">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<input name="name" type="text" class="form-control rounded-lg" required placeholder="Name">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input name="email" type="email" class="form-control rounded-lg" required placeholder="Email">
</div>
</div>
</div>
<div class="form-group">
<textarea name="message" class="form-control rounded-lg" rows="3" required placeholder="Tell us more about your needs........"></textarea>
</div>
<p class="text-center mt-5 mb-0">
<button id="submit-btn" class="btn btn-outline-dark rounded-lg shadow-none d-inline-flex" name="submit" type="submit">Send Message</button>
</p>
</form>
I had same issue, i resolve with hidden input in form with random name like:
<input type="hidden" name="test">
then in php file:
if(isset($_POST['test'])) {
And work, the issue coming because form.serialize() or new FormData() don't use submit button.
Another way is include button submit like here
You have to remove the action="php/mail.php" method="post" because this is handled by jQuery and you have to add a hidden input like <input type="hidden" name="iamhidden" /> to the form and then replace the if(isset($_POST['submit'])) with if(isset($_POST['iamhidden']))

Displaying form confirmation message on form submit

Thought you might be able to help with this, as I sort of know what I want and how to do it but I am not overally familiar with AJAX/JS and after a certain point I just stopped taking stuff in.
Basically, I am trying to have some text appear when a user submits a form, but obviously only when the form is successfully sent. My HTMl and PHP are below, but I have no idea what I am doing beyond this point so maybe someone can give me a little hand.
<form name="contactform" action="includes/contactprocess.php" method="post">
<div class="form-group">
<input type="text" class="form-control" id="fname" name="fname" required placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control" id="sname" name="sname" required placeholder="Last Name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" required placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" required placeholder="Message Subject">
</div>
<div class="form-group">
<textarea rows="3" name="comment" class="form-control" required placeholder="Enter Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the PHP thus far:
<?php
/* Set e-mail recipient */
$myemail = "myemailhere";
/* Check all form inputs using check_input function */
$fname = check_input($_POST['fname'], "Enter your first name");
$sname = check_input($_POST['sname'], "Enter your second name");
$subject = check_input($_POST['subject'], "Enter the message subject");
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Enter the message you wish to be sent");
/* Error handling and sanitisation for email */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("The e-mail you have entered is not valid");
}
/* Let's prepare the message for the e-mail */
$message = "A contact form has been submitted by;
Name: $fname
Surname: $sname
E-mail: $email
Comments:
$comment
Message sent via myemailhere
";
/* Send message via mail function */
mail($myemail, $subject, $message);
if(mail($myemail, $subject, $message)) {
$data['success'] = true;
}
else{
$data['success'] = false;
}
// convert the $data to json and echo it
// so jQuery can grab it and understand what happend
echo json_encode($data);
/* Check input */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
The JS/AJAX I don't really understand:
<script>
$(document).ready(function() {
// hide the success message
$('#success').hide();
// process the form
$('form').submit(function(event) {
// get the form data before sending via ajax
var formData = {
'name' : $('input[name=name]').val(),
'number' : $('input[name=number]').val(),
'message' : $('input[name=message]').val(),
'contactSubmit' : 1
};
// send the form to your PHP file (using ajax, no page reload!!)
$.ajax({
type: 'POST',
url: 'file.php', // <<<< ------- complete with your php filename (watch paths!)
data: formData, // the form data
dataType: 'json', // how data will be returned from php
encode: true
})
// JS (jQuery) will do the ajax job and we "will wait that promise be DONE"
// only after that, we´ll continue
.done(function(data) {
if(data.success === true) {
// show the message!!!
$('#success').show();
}
else{
// ups, something went wrong ...
alert('Ups!, this is embarrasing, try again please!');
}
});
// this is a trick, to avoid the form submit as normal behaviour
event.preventDefault();
});
});
</script>

ajax contact form does not send email

All day i trying to solve the problem but without success.
The form does not send a message and not written an error.
form.html
<div class="ok" id="ok"></div>
<div id="data">
<div id="alert" class="alert_ig"></div>
<form id="form" class=" clearfix" method="POST" action="">
<div class="col-sm-12">
<div class="form-group">
<input name="name" type="text" id="name" value="{$smarty.cookies.nameuser}" class="form-control" placeholder="Name"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input name="email" type="email" id="email" value="{$smarty.cookies.emailuser}" class="form-control" placeholder="E-mail"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<textarea id="message" class="form-control" rows="5" name="text" placeholder="Message"></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<button style="margin-top:10px" id="submit" type="submit" class="bot_g">Send</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#submit').click(function(e){
var form = $(this);
var error = false;
if (!error) {
var data = form.serialize();
$.ajax({
type: 'POST',
url: '{$home}/system/modules/contacts/send.php',
dataType: 'json',
data: data,
success: function(data){
if (data.error.length > 0) {
$('#alert').html(""+data['error']+"");
$('#email').addClass("fill");
} else {
$('#ok').html('send.');
$( "#data" ).css( "display","none" );
}
},
return false;
)};
});
</script>
</div>
send.php
<?php
require_once '../../inc/core.php';
$name=Text(trim($_POST['name']));
$email=Text(trim($_POST['email']));
$subject=Text(trim($_POST['subject']));
$text=Text(trim($_POST['text']));
if(empty($name)){
$json['error'] = 'Come on, you have a name don\'t you?';
echo json_encode($json);
exit;
}
if (mb_strlen($name) < 2 || mb_strlen($name) > 250){
$json['error'] = 'Your name must consist of at least 2 characters!';
echo json_encode($json);
exit;
}
if(empty($email)){
$json['error'] = 'No Email, No Message!';
echo json_encode($json);
exit;
}
if (mb_strlen($email) < 5 || mb_strlen($email) > 64){
$json['error'] = 'Your email must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$json['error'] = 'Unknown characters in your e-mail!';
echo json_encode($json);
exit;
}
if(empty($subject)){
$json['error'] = 'Um...yea, you have to write something to send this form.';
echo json_encode($json);
exit;
}
if (mb_strlen($subject) < 5 || mb_strlen($subject) > 250){
$json['error'] = 'Your subject must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (mb_strlen($text) < 2 || mb_strlen($text) > 10000){
$json['error'] = 'Thats All? Really?';
echo json_encode($json);
exit;
}
$mailer = new phpmailer();
$mailer->ContentType = "text/html";
$mailer->From = $email;
$mailer->Subject = 'New message from '.$home;
$mailer->Body ="Subject: ".$subject."<br/>
Name: ".$name."<br/>
E-mail: ".$email."<br/>
".nl2br($text);
$mailer->AddAddress($setup['emailadmin'], '');
$mailer->Send();
$json['error'] = 0;
echo json_encode($json);
?>
When is my problem with this code?
I must use this send.php format, but may to change ajax and html form to working...
thanks
var form = $(this);
In this line $(this); refers to the submit button so var form, stores your submit button instead of the form element itself.
You may not see an error on the client-side, but if you try to debug the data sent to your server-side you will see something is wrong.
Try replacing $(this) with the selector that matches your form element.
Also, if you want to inform your users when the server returns an error like a 500 error for example, you can add an error callback to your $ajax function, along with the success callback you already have.
Have a look here http://api.jquery.com/jquery.ajax/ for the documentation.
Also add e.preventDefault() at the end of your event handler, to prevent the default action of submitting the form if you want to do an ajax submit.

Ajax URL with variable form location

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.
I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.
This should be the minimum needed code to show my issue.
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
echo json_encode($errors);
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "action.include.php",
dataType: "json",
success: function(data){
alert(data);
}
})
});
</script>
<!-- END Action Form -->
My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.
My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.
not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php
Try with this...
<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){
$name = strip_tags($_POST['name']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$errors = array();
//Validate input
//Name
if(!empty($name)) {
//Check to see that $name only contains valid characters
if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; }
}else{
$errors[] = "Name field must be filled out.";
}
//End Name
//Phone
if(!empty($phone)) {
}else{
$errors[] = "Phone field must be filled out.";
}
//End Phone
//Email
if(!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
}else{
$errors[] = "Email field must be filled out.";
}
//End Email
exit(json_encode($errors)); // exit so it doesn't send the form below
}
?>
<!-- Action Form -->
<section id="sectActionForm">
<div class="row">
<div class="col1 col-md-6">
<img class="noPad" src="/images/banners/karateka.jpg">
</div>
<div id="col2" class="col-md-6 col-xs-12">
<form id="actionForm" class="" role="form" action="index.php" method="POST">
<h3>Get your FREE class today!</h3>
<input id="name" class="form-control" type="text" placeholder="Name" /><br/>
<input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>
<input id="email" class="form-control" type="text" placeholder="Email" />
<input class="btn btn-lg btn-block" type="submit" value="Send" />
</form>
</div>
</div>
</section>
<script type="text/javascript">
$("#actionForm").on('submit', function(event){
event.preventDefault(); // so it doesnt reload the page
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
dataType: "json",
success: function(data){
alert(data);
}
});
});
</script>
<!-- END Action Form -->
Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?
EDIT:
Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

Categories

Resources