PHPMailer Contact Form with Jquery - javascript

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']))

Related

How to fix Sweetalert 2 NOT working in Google Chrome

I am trying to utilize SWEETALERT2 via php on my project but when i try to run my file in google chrome it doesn't work. The buttons are clickable and it records the data but sweetalert doesn't display anything just a clickable submit button.
Things that i want to achieve on this project is to use sweetalert display when i successfully record new user. When i need to update the record or to delete a file.
Submit button should not be clickable if input box has no value.
index.php
<div class="modal-body">
<form action="add_main_users.php" id="form">
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Full Name:</label>
<input type="text" class="form-control" name="fname" required data-validation-required-message="This field is required">
</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Username:</label>
<input type="text" class="form-control" name="uname" required data-validation-required-message="This field is required">
</div>
div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Email:</label>
<input type="email" class="form-control" name="email" required data-validation-required-message="This field is required">
</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Default Password:</label>
<input type="text" class="form-control" name="dpass" required data-validation-required-message="This field is required">
</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Role:</label>
<select class="form-control custom-select" name="role" required data-validation-required-message="This field is required">
<option value="Administrator">Administrator</option>
<option value="Editor">Editor</option>
</select>
</div>
<div class="controls">
<label for="recipient-name" class="control-label" style="color: Grey">Branch Assigned:</label>
<select class="form-control custom-select" name="bassign" required data-validation-required-message="This field is required">
<option value="0">1Warehouse</option>
<option value="1">2Warehouse</option>
<option value="2">3Warehouse</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnSubmit">Submit</button>
</div>
</div>
</form>
</div>
</div>```
add_main_users.php
<?php
$request = $_REQUEST;
$fname = $request['fname'];
$uname = $request['uname'];
$email = $request['email'];
$dpass = $request['dpass'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dims";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$sql = "INSERT INTO users (u_name, u_username, u_email, u_password)
VALUES ('".$fname."', '".$uname."', '".$email."', '".$dpass."')";
if ($mysqli->query($sql)) {
echo "New user has been created.";
} else {
return "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
js
function save()
{
$("#btnSubmit").on("click", function() {
var $this = $(this); //submit button selector using ID
var $caption = $this.html();// We store the html content of the submit button
var form = "#form"; //defined the #form ID
var formData = $(form).serializeArray(); //serialize the form into array
var route = $(form).attr('action'); //get the route using attribute action
// Ajax config
$.ajax({
type: "POST", //we are using POST method to submit the data to the server side
url: route, // get the route value
data: formData, // our serialized array data for server side
beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
$this.attr('disabled', true).html("Processing...");
},
success: function (response) {//once the request successfully process to the server side it will return result here
$this.attr('disabled', false).html($caption);
// Reload lists of employees
all();
// We will display the result using alert
Swal.fire({
icon: 'success',
title: 'Success.',
text: response
});
// Reset form
resetForm(form);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// You can put something here if there is an error from submitted request
}
});
});
}
function resetForm(selector)
{
$(selector)[0].reset();
}
$(document).ready(function() {
// Submit form using AJAX To Save Data
save();
});
function save($this, $caption, form, formData, route) {
// Ajax config
$.ajax({
type: "POST", //we are using POST method to submit the data to the server side
url: route, // get the route value
data: formData, // our serialized array data for server side
beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
$this.attr('disabled', true).html("Processing...");
},
success: function (response) {//once the request successfully process to the server side it will return result here
$this.attr('disabled', false).html($caption);
// Reload lists of employees
all();
// We will display the result using alert
Swal.fire({
icon: 'success',
title: 'Success.',
text: response
});
// Reset form
resetForm(form);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// You can put something here if there is an error from submitted request
}
});
};
$(document).ready(function() {
$("#btnSubmit").on("click", function() {
var $this = $(this); //submit button selector using ID
var $caption = $this.html();// We store the html content of the submit button
var form = "#form"; //defined the #form ID
var formData = $(form).serializeArray(); //serialize the form into array
var route = $(form).attr('action'); //get the route using attribute action
// Submit form using AJAX To Save Data
save($this, $caption, form, formData, route);
})
});

Returning to Original Page with success Mesaage. Boostramp + PHPMailer

I am trying to make it so when the user enters my contact form instead of being redirected to the "mail.php" file they are just shown a message which shows that the message has been sent successfully on the same page. I have tried many tutorials with JS and I am still not sure how to do this.
The PHP Mailer and the Html work, its just the javascript that is meant to show the users the success or failure message which isn't working.
I originally tried to put the JS in a different file and then just call it as a different script at the bottom of the page below jQuery, but this did not work I will probably move it back to its own file.
My HTML currently looks like
<div class="form-container">
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form" >
<div class="row">
<div class="col-md-6" style="padding-right: 4px;">
<input type="text" name="first_name" id="name" placeholder="Name" required />
</div>
<div class="col-md-6" style="padding-left: 4px;">
<input type="email" name="email" id="email" placeholder="Email" oninvalid="this.setCustomValidity('Please enter valid email address.')" onchange="this.setCustomValidity('')" required />
</div>
</div>
<input type="text" name="subject" id="subject" placeholder="Why are you contacting me?" required />
<textarea name="message" id="message" cols="30" rows="10" placeholder="Tell me more about your propersition?" required></textarea>
<input type="submit" id="submit" name="submit" value="submit">
<label class="checkbox-label">
<input type="checkbox" id="tos" name="tos" oninvalid="this.setCustomValidity('Please read the Terms of Service.')" onchange="this.setCustomValidity('')" required>
<span class="checkbox-custom rectangular"></span>
</label>
<label for="tos">I agree to the Terms of Service</label>
</form>
</div>
My PHP mailer file (Mail.php) currently looks like
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; // Enable verbose debug output
$mail->isSMTP(); // Send using SMTP
$mail->Host = 'mail.edbrook.site'; // Set the SMTP server to send through
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'info#edbrook.site'; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('info#edbrook.site', 'Web Contact');
$mail->addAddress('ed#edbrook.site', 'Admin - Edbrook.site'); // Add a recipient
// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for your message. We will get back to you soon!';
// If something goes wrong, we will display this message.
$errorMessage = 'There was an error. Please try again later!';
//Content
$mail->isHTML(true); // Set to HTML
$mail->Subject = 'Contact Form Message';
$mail->Body = "Full Name: ".htmlspecialchars($_POST['first_name'])."<br />Email Address: ".htmlspecialchars($_POST['email'])."<br /><br />";
$mail->send();
$responseArray = array('type' => 'success', 'message' => $okMessage);
} catch (Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
} catch (Error $e) {
// should log the fatal
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
And the javascript currently looks like
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
// if the validator good
if (!e.isDefaultPrevented()) {
var url = "mail.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// apply success/danger
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('The ajax request failed:' + errorThrown);
}
});
return false;
}
})
});
It is mainly copied from online but I do not really need a validator as its already handled within jQuery so doesn't need to be done again I just need the error/success message to be shown on the contact.php page rather than it being redirected to a blank page.
Thank you :)
Here is fully working code you. There are few issues in your ajax and HTML
You need set dataType: json in your $.ajax request because the response you are getting back from the PHP file is json format.
Your HTML does not contain any .messages div where a success or error message will be displayed
In addition you need to use this => $('#contact-form').submit(function(e){}) for form submission and use e.preventDefault() to make sure that page does not reload on form submission
I assume that your PHPMailer is working perfectly and is sending email already. You just need to use this following HTML and jQuery code so that the success message is displayed on the contant.php pages rather then on another page.
I have tested my code on localHost and is working perfectly and sending email with the correct form information data as well.
jQuery
$(function() {
$('#contact-form').submit(function(e) {
e.preventDefault()
var url = "mail.php";
//POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
// data = JSON object that contact.php returns
// apply success/danger
var messageAlert = 'alert-' + data.type;
var messageText = data.message
// Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable" role="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>'
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('.form-container').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('The ajax request failed:' + errorThrown);
}
});
return false;
})
});
HTML
<div class="form-container">
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form">
<div class="row">
<div class="col-md-6" style="padding-right: 4px;">
<input type="text" name="first_name" id="name" placeholder="Name" required />
</div>
<div class="col-md-6" style="padding-left: 4px;">
<input type="email" name="email" id="email" placeholder="Email" oninvalid="this.setCustomValidity('Please enter valid email address.')" onchange="this.setCustomValidity('')" required />
</div>
</div>
<input type="text" name="subject" id="subject" placeholder="Why are you contacting me?" required />
<textarea name="message" id="message" cols="30" rows="10" placeholder="Tell me more about your propersition?" required></textarea>
<input type="submit" id="submit" name="submit" value="submit">
<label class="checkbox-label">
<input type="checkbox" id="tos" name="tos" oninvalid="this.setCustomValidity('Please read the Terms of Service.')" onchange="this.setCustomValidity('')" required>
<span class="checkbox-custom rectangular"></span>
</label>
<label for="tos">I agree to the Terms of Service</label>
</form>
<div class="messages"></div>
</div>
There are couple of things you need to change.
If you do not want to redirect to mail.php, then remove it from the form's action attribute. Since you are injecting success/failure message via JavaScript, add onsubmit="return false;" so prevent page refresh.
<form id="contact-form" method="post" action="" name="contact-form" role="form" onsubmit="return false;">
I can't see a div with class name as messages in your HTML.
Add e.preventDefault() Inside
$('#contact-form').on('submit', function (e) {
e.preventDefault(); // here
Add a new <div> inside <form> tag:
<form id="contact-form" method="post" action="mail.php" name="contact-form" role="form" >
<div class="messages"></div>

Has Post request a limited number of parameters?

I'm trying to send to my server 5 parameters:
Action: will contain the name of the form, in this case "signin"
Name: Name of the person who wants to signin
Surname: Surname of the person who wants to signin
Email: Email of the person who wants to signin
Password: Password of the person who wants to signin
the problem is that my server reads only 4 parameters: Name, Surname, Email and Password, and it don't see Action!
Here's the code:
Javascript:
function signin() {
alert("OK");
var action = $(this).attr('name'); // puts in action the name of the form (this case "signin")
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: document.getElementById('signin-name').value, // Name in the form
Surname: document.getElementById('signin-surname').value, // // Surname in the form
Email: document.getElementById('singin-email').value, // Email in the form
Password: document.getElementById('singin-password').value // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
PHP - Signin.php:
<!-- Signin Form -->
<?php
require('include/header.php');
?>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
<?php require('include/footer.php');?>
PHP - Submit.php:
<?php
#Detect AJAX and POST request, if is empty exit
if((empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') or empty($_POST)){
exit("Unauthorized Acces");
}
require('inc/config.php');
require('inc/functions.php');
# Check if Login form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-login'){
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$email = $_POST['Email'];
$password = $_POST['Password'];
/* Server side PHP input validation */
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Checking Email and Password existence in DB
# Selecting the email address of the user with the correct login credentials.
$query = $db->query("SELECT Email FROM USERS WHERE Email='$email' AND Password='$password'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if($query->rowCount() == 1) {
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
} else {
# Failure: Set error message
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
# Check if Registration form is submitted
if(!empty($_POST) && $_POST['Action'] === 'form-signin') {
# Define return variable. for further details see "output" function in functions.php
$Return = array('result'=>array(), 'error'=>'');
$name = $_POST['Name'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$password = $_POST['Password'];
# Server side PHP input validation
if($name === '') {
$Return['error'] = "Please enter Full name.";
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$Return['error'] = "Please enter a valid Email address.";
} else if($password === '') {
$Return['error'] = "Please enter Password.";
}
if($Return['error']!='') {
output($Return);
}
# Check Email existence in DB
$result = $db->query("SELECT Email FROM USERS WHERE Name='$name' AND Surname='$surname' AND Email='$email'");
if($result->rowCount() == 1){
# Email already exists: Set error message
$Return['error'] = 'You have already registered with us, please login.';
}else{
# Insert the new user data inside the DB
try{
$db->query("INSERT INTO `users` (`ID_user`, `Name`, `Surname`, `Email`, `Password`) VALUES (NULL, '$name', '$surname', '$email', '$password')");
}
catch (PDOException $e) {
echo $e->getMessage();
}
# Success: Set session variables and redirect to Protected page
$Return['result'] = $_SESSION['UserData'] = $result;
}
output($Return);
}
PHP - Functions.php
# Function to set JSON output
function output($Return=array()){
header('Content-Type: application/json; charset=UTF-8');
#exit(json_encode($Return)); # Final JSON response
echo json_encode($Return);
}
here is a screenshot of the debugger:
Debug Screenshot
function signin() {
alert("OK");
var action = $('#form-signin').attr('name'); // puts in action the name of the form (this case "signin")
// alert(action);
$.ajax({
type: "POST",
url: "submit.php",
data: {
Action: action, // the server don't see it!!
Name: $('signin-name').val(), // Name in the form
Surname: $('signin-surname').val(), // // Surname in the form
Email: $('singin-email').val(), // Email in the form
Password: $('singin-password').val() // // Password in the form
},
cache: false,
success: function() {
alert("success");
window.location.href = "index.php"; // load the index.php page, which contains the login form
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limiter">
<div class="form-container">
<div class="form-wrap">
<form action="submit.php" method="post" name="form-signin" id="form-signin" autocomplete="off">
<span class="form-title">Registration form</span>
<div class="form-field">
<label for="Name">Name</label>
<input type="text" name="Name" id="signin-name" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="Surname">Surname</label>
<input type="text" name="Surname" id="signin-surname" class="form-control" required pattern=".{1,100}" autofocus>
</div>
<div class="form-field">
<label for="email">Email address</label>
<input type="email" name="Email" id="signin-email" class="form-control" required>
</div>
<div class="form-field">
<label for="Password">New password</label>
<input type="password" name="Password" id="signin-password" placeholder="Almeno 6 caratteri" class="form-control">
</div>
<div id="display-error" class="alert alert-danger fade in"></div><!-- Display Error Container -->
<div class="form-submit-container">
<div class="form-submit-wrap">
<button class="form-cancel-button" type="submit">Cancel</button>
<button class="form-submit-button" type="submit" onclick="signin()">Signin</button>
</div>
</div>
</form>
</div>
</div>
</div>
The problem is with your scope for $this. Since your Javascript is called within a BUTTON element, $this has a scope relative to the button, not the form. In trying to check what $this returns by itself, it says [object Window].
function signin() {
console.log(this);
}
Console:
[object Window]
You need to either pass this via signin(this) and backtrack to the containing form element if you plan on reusing the Javascript for other forms or just use the form id in place of this.
HTML:
<button onclick="signin(this)">
JS:
function signin(element) {
var action = element.form.getAttribute("name");
}
or just simply change the this to the form's id as Lakmal pointed out:
function signin() {
var action = $("#form-signin").attr("name");
}

Php Ajax Form is not submitting

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.

How can i submit hidden values to php using AJAX

i am trying to send some values from html form to php page.
here in the form i have some values which are hidden.and one text field which its value has to be passed to php page.
index.php:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="friend-invite.php" method="get">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="submit" name="submit" value="Invite" class="btn btn-primary">
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
friend-invite.php:
<?php
include('_header.php');
$user_email = $_GET['friendemail'];
$invited_by = $_GET['invitename'];
$invite_link = $_GET['invite-url'];
$product_name = $_GET['invite-product-name'];
if (isset($user_email, $invited_by, $invite_link, $product_name)){
sendInvitation($user_email,$invited_by,$invite_link,$product_name);
} else {
echo "Are you trying to do something nasty??";
}
function sendInvitation($user_email,$invited_by,$invite_link,$product_name)
{
$mail = new PHPMailer;
if (EMAIL_USE_SMTP) {
$mail->IsSMTP();
$mail->SMTPAuth = EMAIL_SMTP_AUTH;
if (defined(EMAIL_SMTP_ENCRYPTION)) {
$mail->SMTPSecure = EMAIL_SMTP_ENCRYPTION;
}
$mail->Host = EMAIL_SMTP_HOST;
$mail->Username = EMAIL_SMTP_USERNAME;
$mail->Password = EMAIL_SMTP_PASSWORD;
$mail->Port = EMAIL_SMTP_PORT;
$mail->IsHTML(true);
} else {
$mail->IsMail();
}
$mail->From = EMAIL_VERIFICATION_FROM;
$mail->FromName = $invited_by;
$mail->AddAddress($user_email);
$mail->Subject = SHOP_INVITE;
$link = $invite_link;
$mail->Body = $invited_by." ".FRIEND_INVITE_PRODUCT."<a href='".$link."'>".$product_name."</a>";
if(!$mail->Send()) {
$this->errors[] = MESSAGE_VERIFICATION_MAIL_NOT_SENT . $mail->ErrorInfo;
return false;
} else {
return true;
}
}
?>
AJAX function:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
the friend-invite.php page is getting the values that has been passed to it and check if the values has been set, if it has been set then it will call the php function sendInvitation() with the parameters. now all these things are happening pretty good.but i want to do it through AJAX. how can i do that.
You forgot to give your hidden fields an id:
echo '<input type="hidden" name="invitename" id="invitename" value="'.$_SESSION["user_name"].'">' ;
...
Change your index.php as:
<?php
if ($login->isUserLoggedIn() == true){
?>
<div class="panel panel-default">
<div class="panel-heading"><h4>Invite friend</h4></div>
<div class="panel-body">
<form action="">
<div class="col-md-4 col-lg-4">
<label class="control-label" for="friend">Enter email address</label>
<input type="email" class="form-control" name="friendemail" id="friendemail" placeholder="sam#uncle.com" required><br>
<?php
echo '<input type="hidden" name="invitename" value="'.$_SESSION["user_name"].'">' ;
echo '<input type="hidden" name="invite-url" value="'.$_SERVER['REQUEST_URI'].'">';
echo '<input type="hidden" class="invite-product" name="invite-product-name">';
?>
<input type="button" id="btn-submit" name="submit" value="Invite" class="btn btn-primary" />
</div>
</form>
<div class="mail-message"></div>
</div>
</div>
<?php
}else{
}?>
And change AJAX function as:
$(function () {
$('#btn-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'invite-friend.php',
data: $('form').serialize(),
success: function () {
$(".mail-message").html('<div class="alert alert-success"><strong>Success!</strong> Indicates a successful or positive action.</div>');
}
});
});
});
We do not need a submit button in form if we using AJAX.
Dude you are simply making your code complex ... you are doing form submit + ajax submit .I think there you are going wrong.
Just try these:
Remove action="friend-invite.php" from your form tag and try . if this does not help than make your button input type button or use button tag. just try all these it should work.
If all this does not work than give id and name to your form ,,and use to submit as:
$(function() {
$("#form_id").on("submit", function(event) {
Try all these

Categories

Resources