Form, AJAX and PHP - 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!

Related

php ajax insert shows blank response but no error

I am simply inserting a demo data by ajax form to database. The ajax shows no error but shows blank response when i use console.log(response);.
Php code-
<form role="form" id="signup_form">
<div class="row">
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label class="required">First Name</label>
<div class="input-with-icon">
<input type="text" class="form-control" placeholder="Your First Name"
name="f_name" id="f_name" required>
<i class="ti-user"></i>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" name="submit"
class="btn btn-md full-width btn-theme-light-2 rounded">Sign Up</button>
</div>
</form>
ajax code-
<script>
$(document).ready(function() {
$("#submit").on("click", function(e) {
e.preventDefault();
var f_name = $('#f_name').val();
console.log(f_name); // <--- but this shows the typed data from the form
$.ajax({
url: "homes/php/user-signup.php",
method: "POST",
data: {
"f_name": f_name
},
success: function(response) {
$('#signup_form')[0].reset();
$('#signup').modal('hide');
console.log(response); // <--- this shows blank response
},
error: function(response) {
console.log(response);
}
});
});
});
</script>
mysql --
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['submit'])){
$f_name=$_POST['f_name'];
$query = "INSERT INTO `user_info`(`first_name`) VALUES (':f_name')";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name',$f_name);
$stmt->execute();
}
?>
You're echoing a script block in the response, which makes no sense in an AJAX context.
Also you're not echoing any content in anything except the pure success case, and you're checking for the wrong variable in $_POST - your AJAX code only sends "f_name" to the server, nothing else.
You also have a typo in your SQL query - :f_name should not in in quote marks within the SQL string.
This should give you more feedback:
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['f_name']))
{
$query = "INSERT INTO `user_info`(`first_name`) VALUES (:f_name)";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name', $_POST['f_name']);
if($stmt->execute())
{
echo "Signup Successful";
}
else
{
echo "Error - query did not execute correctly. See error logs for details";
//N.B. You should put some code here to log the real error to a file
}
}
else
{
echo "Missing parameters, please try again";
}
?>
If it still doesn't output anything after that, do some more debugging - check your browser's Console and Network tools to see if the request is even succeeding.
Change this $_POST['submit'] to $_POST['f_name']. It will work. you didn't post submit in ajax request.
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['f_name'])){
$f_name=$_POST['f_name'];
$query = "INSERT INTO `user_info`(`first_name`) VALUES (:f_name)";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name',$f_name);
if($stmt->execute()){
echo "Signup Successfull";
}else{
echo "Insert failed. DB error";
}
}
?>

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

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

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,

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

Preventing form from refreshing page Javascript

im quite bad at javascript, and i am trying to make a AJAX call, but i get my value from a form feild, and it just refreshes the page, cant even observe if the AJAX call is succesfull.
Here is my HTML:
<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
<fieldset>
<p>
Subscribe
</p>
<div class="input-prepend input-append">
<input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
<input type="submit" class="btn btn-inverse" />
</div>
</fieldset>
</form>
JS:
function subscribe() {
var emailForm = $('#subscribwEmail').val();
$('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')
$.ajax({
type: "POST",
url: "../../actions/ajax-subscribe.php",
data: {
email: emailForm
},
dataType: "json",
success: function (data) {
if (data[0] == 1) { // test if response was 1 or 2
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
} else {
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
}
}
})
};
ajax-subscribe.php
<?php
include ('phpfunctions.php');
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');
$email = cleanString($con, $email);
$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";
if ($result = mysqli_query($con, $query)) {
echo json_encode(1); // all ok inserted
} else {
echo json_encode(0); // failed
}
?>
You do not cancel the click event so the form submits.
Add return false; to the end of your subscribe method.
You have to return false from your subscribe method
Also you can validate the email, if it is invalid, you can stop sending subscribe by return false
You can also disable your submit button. (formObj comes with subscribe parameter)
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
But you have to enable it if something goes wrong.

Categories