cant update db on ajax submit php form - php

I can't update my database table on form submit with ajax. I don't know the reason or why this is happening. I posted my code below. Thanks.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ime = !empty($_POST['ime']) ? stripslashes(trim($_POST['ime'])) : '';
$email = !empty($_POST['email']) ? stripslashes(trim($_POST['email'])) : '';
$poruka = !empty($_POST['poruka']) ? stripslashes(trim($_POST['poruka'])) : '';
$ime = htmlspecialchars($_POST['ime']);
$email = htmlspecialchars($_POST['email']);
$poruka = htmlspecialchars($_POST['poruka']);
//Validate Phone
if (empty($_POST["ime"])) {
http_response_code(400);
echo "Molimo, unesite Vaše ime i prezime.";
exit;
}else {
if (!preg_match('/^[a-zA-Z\s]+$/',$ime)) {
http_response_code(400);
echo "Dozvoljena su samo slova i space.";
exit;
}
}
//Validate Email
if (empty($_POST["email"])) {
http_response_code(400);
echo "Molimo, unesite Vaš e-mejl.";
exit;
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Nepravilan e-mejl format";
exit;
}
}
if (empty($_POST["poruka"])) {
http_response_code(400);
echo "Molimo, unesite Vašu poruku.";
exit;
}
if(isset($_POST['submit']) && !empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])){
$link = new mysqli("localhost", "admin", "", "proba");
$stmt = $link->prepare("INSERT INTO message(ime, email, poruka) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $ime, $email, $poruka);
$stmt->execute();
$stmt->close();
$link->close();
$email_message .= "Ime i prezime: ".htmlspecialchars($ime)."\n";
$email_message .= "E-mejl: ".htmlspecialchars($email)."\n";
$email_message .= "Poruka: ".htmlspecialchars($poruka)."\n";
$to = "somemail#mail.com";
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($to, $subject, $email_message, $headers)) {
http_response_code(200);
echo "Poruka je uspešno poslata!";
exit;
} else {
http_response_code(400);
echo "Message is not successfully sent";
exit;
}} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
exit;
}
}
?>
Html
<div class="container">
<h1>Kontakt</h1>
<div id="form-messages"></div>
<form action="mail.php" method="POST" id="form">
<input id="ime" type="text" name="ime" value="<?php echo !empty($ime) ? $ime : ''; ?>" placeholder="Ime i Prezime">
<input id="email" type="text" name="email" value="<?php echo !empty($email) ? $email : ''; ?>" maxlength="20" placeholder="E-mejl">
<textarea name="poruka" id="poruka" placeholder="Poruka" maxlength="700" cols="30" rows="10"><?php echo !empty($poruka)?$poruka:''; ?></textarea>
<input id="submit" type="submit" name="submit" value="Pošalji Poštu">
</form>
</div>
and JQuery
$(function() {
// Get the form.
var form = $('#form');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: 'mail.php',
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#ime').val('');
$('#email').val('');
$('#poruka').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
If anybody has a solution, please do tell. I copied and pasted this amount of code for you to see the context. I don't know where to look for the solution. Thank you.

The reason this does not work via ajax (but does via a conventional postback) is that jQuery's .serialize() method does not serialise button values.
Therefore despite you having name="submit" on your button, its value will not be sent to the server in the request when you make the ajax call. In a conventional postback, it would be, if the button was used as the means to submit the form.
The documentation says:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button.
Although your button click may have triggered the code which submitted the form, it is no longer doing the form submission directly (instead ajax is doing it). In theory this could be triggered by anything, and jQuery has no way of knowing it was the button which started the process.
See https://api.jquery.com/serialize/ for more detail.
This causes you a problem because you test for the presence of this "submit" value before you make your database call and send your email. It's not really necessary to do this, since you're validating all the other input fields. I think you can just remove isset($_POST['submit']) from your if statement and you will have no problems. Therefore you'll be left with:
if(!empty($_POST['ime']) && !empty($_POST['email']) && !empty($_POST['poruka'])) {

Related

PHP contact form keep input fields if error, otherwise clear

I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.
Here's my form:
<form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>
I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.
Let's assume that your page is contact.php.
You php code should be something like this:
// we will keep here error message
$error = '';
// if request is get and isset sent
if ($_SERVER["REQUEST_METHOD"] === "GET" and isset($_GET["sent"]))
echo '<p id="output-area">Message has been sent.</p>';
else {
// if request is post
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// then verify input data
if (!empty($_POST['msg'])) {
// if mail was sent, redirect to contact.php?sent
if (mail("someone#example.com", "My subject", $_POST['msg'])){
header('Location: contact.php?sent');
exit;
} else
$error = "Mail does not sent.";
} else
$error = 'Please fill in all inputs.';
}
}
if ($error != '')
echo '<p class="error">Error: ' . $error . '</p>';
// here goes your form
echo '<form class="contact-form" action="contact.php" method="post">
<textarea name="msg">' . (!empty($_POST["msg"]) ? $_POST["msg"] : '') . '</textarea>
<input type="submit" value="send">
</form>';
You should set error flag while error occurred. try this
$error=false;
if(isset($_POST['submit'])){
$msg = $_POST['msg'];
if(mail("someone#example.com","My subject",$msg)){
}else{
$error = "mail does not sent";
}
}
" />

POST data sent with ajax doesn't trigger ($_SERVER["REQUEST_METHOD"] == "POST") in 2nd PHP File

I'm trying to make some sort of simple text chat.
I have two PHP files (index.php and send.php) and a javascript script (script.js).
In index.php, i got the following form:
<form id="formSend" method="post">
<input id="inputMsg" class="form-control input-msg" type="text" name="msg" autocomplete="off">
<button id="btnSend" class="btn btn-success button-send" type="submit" name="send">Send</button>
</form>
To prevent the page from reloading, the data is sent with a ajax request in my javascript file:
$('#formSend').submit(function(e){
e.preventDefault();
var url="send.php";
var posting = $.post(url, {msg: $('#input-msg').val() });
posting.done(function(data){
$('#inputMsg').val('');
console.log('success');
});
});
The ajax request works (success is logged in the console), but in send.php
nothing happens.
Im using the following code in send.php:
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['msg']) && !empty(trim($_POST['msg']))){
$msg = htmlspecialchars(trim($_POST["msg"]));
$check = true;
}
else{
$check = false;
}
if ($check = true) {
$query = "INSERT INTO chat(message) values (?)";
$stmt = $mysqli->prepare($query);
if($stmt===false){
$error = 'Database error';
}
if(!$stmt->bind_param('s', $msg)){
$error = 'Database error';
}
if(!$stmt->execute()){
$error = 'Database error' . $mysqli->error;
}
if(empty($error)){
$mysqli->close();
$success = 'Success';
}
}
}
Am i missing something? I really don't know why its not working...
<input id="inputMsg" class="form-contr .... >
And
var posting = $.post(url, {msg: $('#input-msg').val() });
Does not match.
Remove the - and Capitalize M

Clear form fields after a successful submit

well im working on a small html form.
<form class="contact" action="" method="POST">
<label>Name : </label><input type="text" name="name" value="<? echo $name; ?>"/>
<p class="middle"><label>Comment : </label><textarea name="message"></textarea><? echo $message; ?></p>
<label class="captcha"><img src="captcha.php" style="line-height: 30px;"></label><input type="text" name="code"/>
<input type="submit" class="csubmit" value="Now !" name="get"/>
</form>
and this is the php code:
<?php
if (isset($_POST['get'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "no name. <br />";
}
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
$error .= "no message <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "wrong captcha <br />";
}
if (!empty($error)) {
echo '<p class="error">Error :<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
if (empty($error)) {
$message = mysql_real_escape_string($message);
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($_GET['id']);
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO comments(id, name, comment, time,approved)VALUES('$id', '$name', '$message', '$date', '0')");
echo "thank you";
}
}
?>
As you can see i user $message and $name to keep informations after a submit with wrong captcha code, but the problem is that i want to clear those fields after a submit with correct informations. Can you please tell me how can i clear form fields after a succesfull submit ?
You can use .reset() on your form.
$("#form")[0].reset();
You could follow that with Javascript too
document.getElementById('form').reset();
Or, if successful, redirect the user back to your contact page:
header("Location: contact.php"); // redirect back to your contact form
exit;
EDIT
<input type="submit" class="csubmit" value="Now !" name="get" onClick="clearform();" />
function clearform()
{
document.getElementById("name").value=""; //don't forget to set the textbox ID
document.getElementById("message").value=""; //don't forget to set the textbox ID
document.getElementById("code").value=""; //don't forget to set the textbox ID
}
Also use:
required="required"
so people will be required to fill out the input fields :)
Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

Unchecked Checkbox is causing AJAX Feedback to hang (with spinning loading icon)

Paul here. I'm working on a simple form with one checkbox, a textarea and some inputs. I got POST to database to work on my localhost, I can submit all form data successfully, but having trouble when a checkbox in my form is unchecked: feedback fails, it says 'please wait' and just spins. The database registers the data okay in either case, but I would appreciate any help to get it more responsive.
The main problem occurs when user leaves 'subscribe' unchecked: no feedback.
I'm also hoping to learn how to create deeper feedback, such as "Your message has been sent. We'll be in touch shortly. You have also been added to our mailing list."
Here is my php:
<?php
/*Contact Form*/
//ajax call
if(isset($_GET['action'])&& $_GET['action'] == 'contact'){
mysql_connect('localhost','******','**********');
mysql_select_db('*******');
//sanitize data
$email = mysql_real_escape_string($_POST['contact-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = 'error';
$message = 'You did not enter an email address!';
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingContact = mysql_query("SELECT * FROM contact WHERE contact_email_address='$email'");
if(mysql_num_rows($existingContact) < 1){
//database insert code
$message = $_POST['contact-textarea'];
$checkbox = $_POST['contact-checkbox'];
$name = $_POST['contact-name'];
$date = date('Y-m-d');
$time = date('H:i:s');
$insertContact = mysql_query("INSERT INTO contact (contact_email_address, contact_date, contact_time, contact_name, contact_message, contact_checkbox) VALUES ('$email','$date','$time','$name','$message','$checkbox')");
if($insertContact){
$status = 'success';
$message = 'your message has been received';
}
else {
$status = 'error';
$message = "Oops, there's been a technical error!";
}
}
else {
$status = 'error';
$message = 'This email address has already been registered!';
}
}
//return the JSON response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
and here is my html:
<form id="contact-form" action="?action=contact" method="post">
<legend>Contact us:</legend>
<label for="email">Your email: *</label>
<input type="email" name="contact-email" id="contact-email" placeholder="Your email here..." required></input>
<label for="name">Your Name: *</label>
<input type="name" name="contact-name" id="contact-name" placeholder="Your name here..." required></input>
<label for="message">Your Message: *</label>
<textarea id="contact-textarea" name="contact-textarea" placeholder="Type your message here..." rows = "8" cols = "35" required></textarea>
<label for="checkbox">Subscribe to Newsletter?</label>
<input type="checkbox" name="contact-checkbox" id="contact-checkbox" value="1"></input>
<p id="contact-response"></p>
<input type="submit" name="contact-button" id="contact-button"></input>
</form>
and here's the javascript:
$(document).ready(function(){
$('#contact-form').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#contact-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formsstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
})
My best guess is that it has to do with the fact that jQuery.serialize does not serialize the checkbox if it is unchecked.
Compare:
Checked: contact-email=test%40gmail.com&contact-name=test&contact-textarea=test&contact-checkbox=1
Unchecked: contact-email=test%40gmail.com&contact-name=test&contact-textarea=test
As a result, $_POST['contact-checkbox'] returns null which probably changes the data that's being returned to include a PHP warning, which breaks the JSON you're returning. To fix it, try this (I'm not fully sure it'll work):
if ( isset($_POST['contact-checkbox']) ) {
$checkbox = $_POST['contact-checkbox'];
}
else {
$checkbox = 0;
}
This checks if the contact checkbox is being posted. If so, if sets the checkbox value to the POST value. If not, the checkbox's set to 0.

Form submitting with jQuery and sending with PHP.. Can't work out why its not sending

Console is not showing any errors, neither is Firebug so I'm at a loss as to why this isn't working.
My form:
<form action="" method="post" id="sendEmail">
<div class="alignleft">
<p><label for="order_ref">Photo ID:</label><input type="text" name="order_ref" id="order_ref" class="text smallinput" disabled="disabled" value="<? echo $ref; ?>"/></p>
<p><label for="order_name">Full Name:</label><input type="text" name="order_name" id="order_name" class="text" tabindex="10" /></p>
<p><label for="order_telephone">Contact Number:</label><input type="text" name="order_telephone" id="order_telephone" class="text" tabindex="20" /></p>
<p><label for="order_email">Email Address:</label><input type="text" name="order_email" id="order_email" class="text" tabindex="30" /></p>
</div>
<div class="alignright">
<p class="higher"><label for="order_message">Message</label><textarea name="order_message" id="order_message" class="uniform" tabindex="40"></textarea></p>
</div>
<div class="rounded color_grey"><p>Clicking confirm will mail your order to us. We'll be in touch shortly. <input type="submit" id="submit" name="submit" value="" class="alignright" /></p></div>
</form>
Then my JS:
// JavaScript Document
var g = jQuery.noConflict();
g(document).ready( function() {
g("#submit").click(function(){
// set initial error value to false
var hasError = false;
// set var for each form field
var order_ref = g("#order_ref").val();
var order_name = g("#order_name").val();
var order_telephone = g("#order_telephone").val();
var order_email = g("#order_email").val();
var order_message = g("#order_message").val();
// validate each of them
if(order_ref == '') { g("#order_ref").addClass('haserror'); hasError = true; }
if(order_name == '') { g("#order_name").addClass('haserror'); hasError = true; }
if(order_telephone == '') { g("#order_telephone").addClass('haserror'); hasError = true; }
if(order_email == '') { g("#order_email").val().addClass('haserror'); hasError = true; }
if(order_message == '') { g("#order_message").val().addClass('haserror'); hasError = true; }
// if there's no errors, proceed
if(hasError == false) {
//alert('no errors');
g.post("/photo/theme/foodphoto/includes/mail_send.php",
{
// pass each of the form values to the PHP file for processing
order_ref: order_ref,
order_name: order_name,
order_telephone: order_telephone,
order_email: order_email,
order_message: order_message
},
function(data){
// no errors? great now do what you want to show the user his message is sent
alert('sent');
}
);
}
return false;
});
});
And the PHP that should send it (mail_send.php)
<?php
// receive & save each of the vars from the AJAX request
$order_ref = $_POST['order_ref'];
$order_name = $_POST['order_name'];
$order_telephone = $_POST['order_telephone'];
$order_email = $_POST['order_email'];
$order_message = $_POST['order_message'];
// setup the email requirements
$to = "email#address.com";
$subject = "Order Has Been Placed";
// what must be in the mail message
$message = "The following order has been placed on your website:";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$order_name.' <'.$order_email.'>';
mail($to, $subject, $message, $headers);
?>
Console reports no PHP issues and Firebug (I am new at using this, so I might have skipped something?) reports no issues...?
What am I doing wrong?
Don't use the .click handler when using an input type of submit. Switch it to
g("#sendEmail").submit(function(){
Then see if when you click submit you invoke the JS as expected.
On a side note, you can reduce the amount of code that you write by serializing your form data with $(FORM ID or CLASS).serialize()
Cheers!
your js code is not called because you added submit button, when hit on that it will submit the form without waiting for a click event to be fired so either you change the button to click and then submit the form from click event or you can use submit an event
Cheers!

Categories