PHP+JQuery+AJAX Form not getting resubmitted with different values - php

This is embarrassing but I cant seem to figure out why my form wont repost after changing the values.
To be clearer, I have this password recovery form in which user enters the email address. The form is processed in PHP through AJAX and a validation/success message is displayed on the form page.
The issue here is that if the user has entered an invalid email address, it displays the error message but if the user then corrects the email address and tries to submit again, it doesn't process the input unless if the page is explicitly refreshed (in which case it shows the resubmission warning which is very annoying). Is there some property that sets the form and needs to be 'un-set' through code? How can I improve this experience? I have posted the code below.
<form id="pwd_rec_form" method="post" action="">
<div class="row">
<div class="large-6 columns">
<input type="email" required placeholder="Email ID" name="email"/>
</div>
</div>
<div id="val_msg" class="row"></div>
<div class="row">
<div class="large-6 columns">
<input id="submit_button" type="submit" value="Send" class="button"/>
</div>
</div>
<div class="row">
<div class="large-6 columns">
Back to login page
</div>
</div>
</form>
<script>
$(function()
{
$("#pwd_rec_form").submit(function()
{
var formdata = $(this).serializeArray();
var hideMsg = function() {$("#val_msg").hide()};
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "recover-password.php",
data: formdata,
success: function(res)
{
$('#val_msg').html(res);
setTimeout(hideMsg, 5000);
}
});
$("#pwd_rec_form").trigger("reset");
return false;
});
});
</script>
PHP :
<?php
include 'db-connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$conn = getDBConnection();
// Check connection
if (mysqli_connect_errno())
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_connect_error() . '
</div>'
);
exit();
}
$eID = mysqli_real_escape_string($conn, trim(strip_tags($_POST['email'])));
$query = 'SELECT password FROM member_login WHERE email_id = "' . $eID . '";';
$result = mysqli_query($conn, $query);
if($result == FALSE)
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_error($conn) . '
</div>'
);
}
else
{
if(mysqli_num_rows($result) == 0) // User not found.
{
echo('<small class="error">This email address is not registered with us.</small>');
}
else
{
$pswd = mysqli_fetch_assoc($result);
//mail the pswd
echo(' <div data-alert class="alert-box success">
Your password has been successfully sent to your registered email address.
</div>'
);
/* free result set */
mysqli_free_result($result);
}
}
mysqli_close($conn);
}
?>

I think your problem is that you have a submit button, which automatically submits the form and refreshes the page, so your javascript doesn't get used. Try making your submit button a type="button" and then changing your jQuery to $("#pwd_rec_form").click(function() and see if that works.

You could hook the form submit, or if you wanted you can hook the click event of the submit button, prevent the default action and instead do your javascript code. Here is an example hooking the "submit_button" click event:
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
Alternative you can do this:
$(document).ready(function() {
$(form).submit(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
The code above just hooks the form on the submit request, prevents the default action, and then you slap your ajax code in there.

I appreciate your help guys. I knew it was something silly. Turns out the form was getting processed but the validation/success messages were not being displayed as the div element that I was hiding using javascript during the first submission needed to be shown again for the second attempt!

Could you try this :
<script>
$(document).ready(function(){
$('#pwd_rec_form').on('submit', function(e){
e.preventDefault();
// insert AJAX call
});
It worked for me, the event is trigged on each click.
Best regards,

Related

Form, AJAX and PHP

I have a simple Subscribe form that I want to get the contents of an 'email' input to post to a MySQL db using AJAX. This is successfully creating a record with the date and time but not inserting the email address.
Can anyone see what's wrong with the following please?
form.php
<form id="subscribe" action="?action=signup" method="post" data-abide>
<div class="row collapse">
<div class="large-10 large-centered columns">
<div class="row collapse postfix-radius">
<div class="small-9 columns">
<div class="email-field">
<input type="email" name="email" id="email" placeholder="Your Email Address" required>
<small style="padding-left:10px; "class="error">Please enter a valid email address</small>
</div>
</div>
<div class="small-3 columns">
<input type="submit" id="button" class="button success postfix" value="Subscribe">
</div>
</div>
</div>
</div>
</form>
<span style="display:none;" id="message"><small><i class="fa fa-check" aria-hidden="true"></i> Subscribed</small></span>
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').submit(function(){
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
</script>
subscribe_insert.php
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Thanks,
John
$(document).ready(function(){
$('#subscribe').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data)
$.ajax({
type: 'post',
dataType: 'JSON',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
replace your code with this then open your browser console and check if the data s getting posted
if you can see the your email there then check if the data is at the server
in you php page copy all the contents from the page and replace
<?php
echo json_encode($_POST)
?>
and once again check console this time you should see data from the server
if both are correct put your original php code back it
Check in your database that email has the correct attributes:
For exaple check that you have at least x characters allowed to be stored, check for the type of the field:
It could be int when it it really should be something like varchar
var_dump details:
form.php is ok for this purpose.
But we are going to modify the php file temporarily to check for "post" error in the email field:
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
var_dump($email); //dump email value
/* comment this peace
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
*/
?>
Now follow the next steps:
Open chrome
Open your webpage
Hit F12
Check the "Log XMLHttpRequests" checkbox
Send your form and you will se something in the console like: XHR finished loading: POST http://localhost//folder/subscribe_insert.php
Click the logged url of your console
You may see a list of resources (depends of your project)
Click the one that has the subscribe_insert.php title
To your right you will see some tabs click response
If there was some error or some data was echoed from that file (In this case our var_dump) you will see it there.
If you see the email actually printing out It might be a database problem as I started tellong you.
I know there are too many steps but it's very fast to do it, I hope I have helped you, greeting!

Ajax code not working even if it is (i think) correct

The function that this do is when the user clicked the button, it will execute the Ajax codes and then get the value of the input and send it to the PHP file and then send it back to the Ajax code to display the message from the MySQL table.
I tried changing my codes, changing div ids, changing syntax, clearing block of codes but none seems to work.
AJAX
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('input[name=message]').val();
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
HTML UPDATED
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<form method="POST">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</form>
</div>
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
PHP UPDATED
<?php
include 'database/connect.php';
session_start();
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$_POST[message]%' OR '$_POST[message]%_' OR '$_POST[message]_'";
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
echo "Hi ". $_SESSION['name'] .".<br> " . $row['message'];
}
?>
Changes with suggestion(in comment):-
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</div><!-- form not requird -->
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
<!-- Add jquery library so that jquery code wiil work -->
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('#msg').val(); // id is given so use that, its more easy
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
automatedchat_func.php(must be in the same working directory where your above html file exist)
<?php
error_reporting(E_ALL);// check all type of error
ini_set('display_errors',1);// display all errors
include 'database/connect.php';
session_start();
$final_result='';//a variable
if(isset($_POST['newmsg']) && !empty($_POST['newmsg'])){// its newmsg not message
$message = $_POST['newmsg'];
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$message%' OR '$message%' OR '$message'"; // check the change ere
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) { // while needed
$final_result .="Hi ". $_SESSION['name'] .".<br> " . $row['message']."<br>";
}
}else{
$final_result .="Hi please fill the input box first";
}
echo $final_result; // send final result as response to ajax
?>
Note:- your query is still vulnerable to SQL Injection. So read for prepared statements and use them

Send php mail using html webform

I have set up a page that is still in construction and i'm building a webform for users to contact me.
When i fill the webform and hit the "send" button, message gets send succesfully and i receieve it on my mail...but when i hit the "send" button, i get re-directed off page, saying it was sent successfully.
How can i prompt user that the message was sent successfully, without getting redirected of page, and get the message in same window?
This is my HTML code
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
<div class="row">
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Name" type="text" required />
</div>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required />
</div>
</div>
<textarea class="form-control" id="message" name="message" placeholder="Message" rows="5"></textarea>
<div class="row">
<div class="col-xs-12 col-md-12">
<button class="btn btn btn-lg">Send Message</button>
</div>
</div>
</form>
And this is my contactUs.php code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$message = <<<EMAIL
$message
From: $name
My email is: $email
EMAIL;
$to = "mymail#mymail.com";
$subject = "New Customer Enquiry";
mail($to, $subject, $message, "From: " . $email);
echo "Thank you, your message has been successfully sent!";
?>
AJAX
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(){
$.post( "assets/php/contactUs.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
});
});
</script>
This is a result of successfully sent message.
Please guys help me out! Thanks!
REDIRECT OPTION
$firstpageurl = 'http://example.com';
echo "Your message has been successfully sent!";
$header('Location: '.$firstpageurl);
Use Ajax as below.Change the submit type button to a normal button by removing the type attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.btn-lg').click(function(event){
$.post( "config.php", $( "#contact" ).serialize(), function(msg){
alert(msg);
} );
event.preventDefault();
});
});
</script>
The action part of your form tag is "assets/php/contactUs.php"
<form action="assets/php/contactUs.php" id="contact" class="form" role="form" method="post">
That means that posting this form will bring you to that page. You can either code that page to send the email and redirect them back like this...
header('Location: '.$firstpageurl);
or put the php code into this first page and remove the entire action property. If you put the php on this page, you need to wrap your code in an if so that people can load the page before posting the form.
if (isset($_POST['email'])){
echo "Sent email";
[email send code here]
}
as for putting the message saying it's sent...that will only work with the second method. To do it without a full page load at all do it with ajax.
You want to use JQuery for that.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#contact").submit(function(){
var form_data=$("form").serialize();
$.post( "assets/php/contactUs.php",form_data, function( data ) {
alert(data);
});
event.preventDefault();
});
</script>
You can do it without using Javascript. Do the following:
Set the form to post to itself (e.g. if your form was on index.php, set action="index.php"
When the page loads, check $_POST to see if the form values were sent.
If the $_POST values are empty, display the form
If the $_POST values are set, do what you need to do with those values, then output your results into the page.
Here's a really simple example demonstrating what I mean.
<?php
$submitted = false;
if (isset($_POST["myinput"]) && $_POST["myinput"] != '') {
$submitted = true;
}
?>
<?php
if ($submitted == false) {
?>
<form action="index.php" method="post">
<input name="myinput"><input type="submit">
</form>
<?php } else { ?>
<h1>Form Submitted</h1>
<?php } ?>

Web form sending duplicate emails

first of all, I know this topic has been discussed in the past but I didn't manage to come to a conclusion, so any help is VERY appreciated.
I know a bit of html but I'm not a programmer, I had someone building a website for me but the web form is often sending duplicate (even 3 or 4 times) emails. I believe (assume) it has to do with people refreshing or hitting the submit button more than once. I tried to disable the 'submit' but I didn't manage to.
At this stage any fix would help. As long as I stop receiving multiple emails from senders.
I will try giving you as much information as possible.
This is the html code for the form:
<div class="form-input">
<div class="form-title">NAME</div>
<input id="form-name" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">EMAIL</div>
<input id="form-email" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">MESSAGE</div>
<textarea id="form-msg" type="text"></textarea>
</div>
<div class="form-input">
<div class="form-title"> </div>
<input id="form-send" type="submit" value="SEND"></input>
</div>
</div><!--end of form holder-->
<div id="details-error">Please comlete all fields and include a valid email</div>
<div id="form-sent">Thankyou for your enquiry - We will be in touch shortly!</div>
</div>
</div>
</div>
</div>
the following is the script I have:
// Contact Form Code
$('#form-send').click(function(){
var name = $('#form-name').val();
var email = $('#form-email').val();
var message = $('#form-msg').val();
var option = $('#form-select').val();
var error = 0;
if(name === '' || email === '' || message === ''){
error = 1;
$('#details-error').fadeIn(200);
}else{
$('#details-error').fadeOut(200);
}
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(email))) {
$('#details-error').fadeIn(200);
error = 1;
}
var dataString = '&option=' + option +'&name=' + name + '&email=' + email + '&text=' + message;
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
return false;
}
});
});
And lastly, the mail.php:
<?php
if ($_POST) {
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$option = $_POST['option'];
$headers = $option . "\r\n" . $name . "\r\n" . $email;
//send email
mail("xxx#email.net", "Mail Enquiry", $text, $headers);
}
?>
If the submit button is being pressed more than once then this may work.
Try adding the following line of code right after $('#form-send').click(function(){
$('#form-send').attr('disabled', 'disabled');
This will disable the submit button after it has been clicked once. If the page is reloaded by the user, it will be enabled.
Note: this code has not been tested.
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
This portion of code in #form-send click function is what to do when the submission was successful, you could modify the submit button to disable further clicks if you feel the users are clicking submit after they already submitted the form.
$('#form-send').attr('disabled','disabled'); // only disable the #form-send and not other forms that may need to still be submitted.
You should change the input to a button:
<input id="form-send" type="submit" value="SEND"></input>
to
<button id="form-send" type="button">SEND</button>
Because otherwise the form will be submitted once through ajax and then again via the form submit/page refresh

php include causing jquery submit function to not work

I'm trying to submit a form. The form is in html I'm using jquery to pass the form to a php page for processing and json_encode to pass back the results to display to the user. If I try to add an incude xxx.php on the php page that jquery is submitting to it kills the whole thing.
Here is how it lays out:
This is the main layout page and includes the form as you can see
<form id="jq_forgot_password" class="forgot_password" action="" method="post" name="password_form">
<?PHP include 'widgets/recover_pass.php'; ?>
</form>
This is the content of the form itself:
<!-- Password Recovery Form-->
<div class="form_text">
<p>
<label for="email">Email:</label>
<input type="email" id="recover_email" name="recover_email" placeholder="Enter your email address" class="field_boarder" value="" size="25px" maxlength="255"/> </p>
<div class="login_button_container">
<input name="login_button" type="submit" class="login_button" value="Submit"/>
</div>
</div>
This is the jquery script that is posting the form data and preventing the default submit button from refreshing the page:
// Forgot Password Validation and Post Function
$(function(){
$("#jq_forgot_password").submit(function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
});
This is the php file that the jquery submit function is submitting to:
<?php
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
This all works fine BUT if I add an include statement at the top of the recover_pass_process.php like this:
<?php
include 'func/user.func.php';
$email_check = '';
$return_arr = array();
if(filter_var($_POST['recover_email'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
$return_arr["email"] = $_POST['recover_email'];
echo json_encode($return_arr);
?>
Then it all comes to a screeching halt even if the included file has nothing in it. Just the fact that I'm trying to include another file kills it.
What am I doing wrong??? Thank you in advance!!
$("#jq_forgot_password").live("submit",function(e){
e.preventDefault();
$.post("widgets/recover_pass_process.php", $("#jq_forgot_password").serialize(),
function(data){
if(data.email_check == 'invalid'){
$('div.message_error').hide();
$('div.message_success').hide();
$('div.message_error').fadeIn();
$('div.message_error').html("<div'> Sorry you must enter a valid e-mail address. Try again.</div>");
} else {
$('div.message_error').hide();
$('form#jq_forgot_password').hide();
$('div.message_success').fadeIn();
$('div.message_success').html("<div'>You're Password has been sent to" + data.email + ". Thank you </div>");
}
}, "json");
});
try this..

Categories