having trouble in showing php success message with ajax - javascript

Here is my below code I'm just trying to send a message form with php script but the message is submitted well. but when it comes to showing success message I'm having trouble page submits the data but shows no code.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#send").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data:{
name: name,
email: email,
message: message,
},
success:function(data) {
$('#msg').html(data);
}
});
});
});
</script>
Below is php and html code:
<?php
include 'db.php';
$name=$_POST["name"];
$email=$_POST["email"];
$message=$_POST["message"];
$query = mysqli_query($con, "INSERT INTO test(name, email, message) VALUES ('$name', '$email', '$message')");
if($query){
echo "Your message has been sent successfully!";
}
else{
echo "Your message has been not sent successfully!";
}
mysqli_close($con);
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name">
<input type="text" class="form-control" id="email" name="email">
<textarea class="form-control" rows="5" id="message" name="message"></textarea>
<button id="send" type="submit" class="btn btn-primary">Send</button>
</form>
<div id="msg" class="alert alert-success hidden"><strong></strong></div>

It is because your form will be submitted as the button has the type submit. By changing the type to button the ajax should be working.
Change type="submit" to type="button"
I hope this will help!

Related

Why cant ajax find php file when submitting form?

I have a form, making an ajax post request but it wont find the php file.Ive tried anything and read through so many posts here and tried everything suggested but nothing helps.
I tried to use an absolute path as that was suggested somewhere. Doesnt work.
relative path doesnt work either
I tried to put the submit button outside of my form in my html file (was suggested in another post) - doesnt work either.
Anyone knows why?
EDIT: Im getting a 404
file structure:
myApp/app/js/contact.js
myApp/app/mail/contact.php
myApp/app/index.html
html:
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
app/js/contact.js:
$('#submit').click(function (event) {
event.preventDefault() ;
var name = $("#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
console.log("name", name, email);
$.ajax({
url: "/app/mail/contact.php",
type: "POST",
data: {
name: name,
email: email,
message: message
}
})
});
mail/contact.php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Contact Form';
$to = 'myemail#yahoo.com';
$subject = 'Message from my page ';
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
}
}
?>
This isn't going to solve your issue, but this is a better ux
give your <form> a class or ID and execute your form submission on a form submit
so it would be
$('.formClassName').submit(function(event){
});
This will allow the form submission to fire off the AJAX event on the submit button click, as well as if the user hits the enter button.
In your html file, put your scripts before </body> tag
<section id="contact">
<form>
name:
<input id="name" type="text" name="name"> email:
<input id="email" type="text" name="email"> message:
<input id="message" type="text" name="message">
<button id="submit">send</button>
</form>
</section>
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/app/js/contact.js"></script>
</body>
Instead of using
url: "/app/mail/contact.php",
use:
url: "mail/contact.php",

"Undefined" response when submitting contact form without page refresh

I am building a basic contact form (three fields) for my site. I have the form built in HTML and CSS; all I had to do was build the PHP to make the form responses send to my email. I found a tutorial and built the PHP file (which worked), but wanted the form to submit in the background and not leave the original page. I found an online tutorial to do that using Ajax, and after some tweaking, I got it mostly to work. The only issue I'm having now is that when I receive the email with the response, the message field is coming back as "undefined."
I have a good grasp on HTML and CSS, but PHP and JS are new to me (just started learning them for this project), so any help on how to fix this issue and possibly correct any wrong code would be a huge help. I've included the form HTML, PHP, and JS below (PHP and JS are both named 'contact.[filetype]'.
HTML
<div id="contact_form">
<form name="contact" action="">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" id="name" required/>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" name="email" id="email" required/>
</div>
<div class="field">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="3"></textarea>
</div>
<ul class="actions">
<li><input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" /></li>
</ul>
</form>
</div>
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
$formcontent="From: $name \n Message: $comments \n";
$recipient = "alltheladsmedia#gmail.com";
$subject = "Message From Website";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html' target='_blank' style='text-decoration:none;color:#505050;'> Return Home</a>";
?>
JS
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name === "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email === "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var message = $("input#message").val();
if (message === "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
$.ajax({
type: "POST",
url: "contact.php",
data: {name:name,email:email,message:message},
success: function() {
$('#contact_form').html("<div id='success'></div>");
$('#success').html("<h2>Your message was successfully submitted!</h2>")
.append("<p>We will get back to you within 24-48 hours.</p>")
.hide()
.fadeIn(1500, function() {
$('#success');
});
}
});
return false;
});
});
In your markup the field's id is "comments" but you are looking for "message" in your JS and PHP.
you have print your mail result
if(#mail($recipient, $subject, $formcontent, $mailheader))
{
echo "Mail Sent Successfully";
}else{
echo "Mail Not Sent";
}
Make few changes if you are using jquery 3.
Change this
$(".button").on("click", function() {
// Validation here
// Put ajax outside this block
});
Edit html form like this code.
Check the dev. tools if the action attribute is added correctly by the php.
<form id="contact" name="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" >
And ajax call into this
$("#contact").on("submit", function(e) {
e.preventDefault(); // Now the page won't redirect
var url = $(this).attr("action");
// Check console if contact is printed after the form is submitted
// If contact is printed the url is right
console.log(url);
$.ajax({
type: "POST",
url: url,
data: $(this).serialiseArray(), // Found a typo here fixed
success: function() {
// Your stuffs
}
});
});
Don't put the ajax call inside the input field verification.
Let me know if you find any issue so I can fix my code.

Angularjs validate

I want validate my form using ajax , but the errors are not showing properly.
Here is my code:
Html
<body ng-app="app" ng-controller="dkController">
<form ng-submit="dk()">
<label>Username</label>
<input type="text" name="username" ng-model="formdata.user">
{{errorName}}
<label>Password</label>
<input type="text" name="password" ng-model="formdata.pass">
<label>Email</label>
<input type="text" name="email" ng-model="formdata.email">
<button type="submit" >Submit</button>
{{message}}
</form>
</body>
Js
function dkController($http,$scope){
$scope.formdata={};
$scope.dk = function(){
$http({
method:"POST",
url:"dk.php",
data:$.param($scope.formdata)
})
.then(function(response){
$scope.errorName = response.data.errors.username;
})
and PHP
$conn= new mysqli('localhost','root','','dangky');
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$sql="SELECT *FROM dangky where username='$username'";
$result= mysqli_query($conn,$sql);
$errors=array();
$data=array();
if(empty($username))
$errors['username']='user name is required';
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
if ($row['username'] == $username){
$errors['check'] = 'Tên đăng nhập đã tồn tại';
}
}
if(!empty($errors)){
$data['success']=false;
$data['errors']=$errors;
}
echo json_encode($data);
Error username is showing but errors check not showing .
This is the php output
{"success":false,"errors":{"username":"user name is required"}} .
The problem is youu passed $scope.formdata which contains
{ user : 'someone', pass: 'abc123!', email: 'me#medotcom' }
Your PHP script is looking for post data { username: 'someone' }
So rename your ng-model to ng-model="formdata.username" or change your PHP to find $_POST['user']. Your choice but they must match.

On form submission hide the form diva and send an email using jQuery

My objective is to send the form data as an email using php and the form div should get replaced by another div. I have done hiding the div part using jquery but not able to send and email. I have also written the code to send email but my issue is how to call the file which has email sending code.
My form code:
<form method="post" id="formsub">
<div id="form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<input type="text" name="email" class="form-control" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="phone" class="form-control" id="phone" placeholder="Phone Number" required>
</div>
<div class="form-group">
<input type="button" id="addbut" name="submit" value="Submit" class="form-control">
</div>
</div>
</form>
My code to hide the div and tried form submission script:
<script>
$(document).ready(function() {
$("#addbut").on('click', function() {
$.ajax({
type: "POST",
url: "fromemail.php",
data: $(form).serialize(),
success: function(){
$("#form").hide();
$("#address").show();
}
});
});
});
</script>
My php email sending code:
<?php
if($_POST['submit']){
$to = "akhil#redd.xyz"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$phone = $_POST['phone'];
$subject = "Spots Contact";
$message = $first_name . ", with " . $phone . "has enquired for the service";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
if(mail($to,$subject,$message,$headers))
{
echo "<script>alert('We will contact you shortly');</script>";
}
}
?>
Give file name in form action attribute :
<form id="formsub" method="post" action="fromemail.php">
and do ajax code like this :
$(document).ready(function(){
var form=$("#formsub");
$("#addbut").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#formsub").serialize(),
success: function(response){
console.log(response);
}
});
});
});
#Rakhi..
Is this correct??
<script type="text/javascript" src="assets/js/jquery-2.2.1.min.js"></script>
<script>
$(document).ready(function() {
var form=$("#formsub");
var base_url = "www.3ding.in/spots/";
$("#addbut").on('click', function() {
$("#form").hide();
$("#address").show();
$.ajax({
type: "POST",
url: base_url + "fromemail.php",
data: $("#formsub").serialize(),
success: function(response){
alert(1);
console.log(response);
}
});
});
});

Captcha is not validating in jquery side..!

I am using php to validate the google REcaptcha..As far as the back-end validation gose is working out fine it giving error if captcha not submitted and if done user is stored in database but major problem arises when i connect it with jquery...thing is it is always giving out error "your missing captcha" every time even if captcha is validated in back-end, please help me out of this, pardon me if am wrong..!!
here gose .php file
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
/*
if required include seperate validation
*/
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
/*
validation process
starts from here
*/
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) >= 6){
//validate your mobile
if(strlen($mobile) == 12){
//validate captcha
//your site secret key
$secret = 'XXXX_secret-key_XXXX';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
}elseif($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
}else{
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}else{
//failed to submit captcha
$response["error"] = true;
$response["error_msg"] = "Sorry this application is not for bots";
echo json_encode($response);
}
}else{
//failed to submit captcha
$response["error"] = true;
$response["error_msg"] = "your missing captcha";
echo json_encode($response);
}
}else{
//invalid mobile number
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
}else{
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
}else{
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
}else{
//missing the required fields
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
Here gose .html file in bootstrap
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MiiSKy | Register</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body class="gray-bg">
<div class="middle-box text-center loginscreen animated fadeInDown">
<div>
<div>
<!--<h3 class="logo-name">MiiSky</h3>-->
<img src="img/landing/mii-logo.png">
</div>
<!--<h3>Register to MiiSky</h3>-->
<p>Create account to see it in action.</p>
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="XXXXX_site-key_XXXXXX"></div>
<!-- End Thumbnail-->
</div>
</div>
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
</form>
here gose the main .js file
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var recaptchaResponse = grecaptcha.getResponse();
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "process.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val(),
recaptchaResponse: recaptchaResponse
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
grecaptcha.reset();
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
First of all make sure that you've included the necessary JavaScript resource to render reCAPTCHA widget properly, like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here's the reference:
Displaying the widget
Now comes to your user's response. The response from the user's captcha challenge can be fetched in three ways. It can be as,
g-recaptcha-response - a POST parameter in the submitted form
grecaptcha.getResponse(widget_id) - will provide the response after the user completes the captcha.
A string argument to the callback function specified in the config object passed to the render method.
Here's the reference:
Verifying the user's response
For you purpose use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again. From the manual:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Here's your HTML code:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="XXXXXX_SITE-KEY_XXXXXXX"></div>
<!-- End Thumbnail-->
</div>
</div>
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var recaptchaResponse = grecaptcha.getResponse();
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "process.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val(),
recaptchaResponse: recaptchaResponse
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
grecaptcha.reset();
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
And finally your PHP should be like this:
<?php
// your code
//your site secret key
$secret = 'XXXXXXX_Secret-key_XXXXXXX';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
}else{
// failure
}
}
// your code
?>

Categories