I have two questions but they are interrelated. Firstly I am trying to make my form fields required. I have accomplished this but it seems my form still calls my php script when the blank form is submitted. How can I make my validation not call the php script if the form is empty?
Secondly, I want to store the url of an image into my database. How can I submit a pre determined string into my database? I have only accomplished database submission with forms.
Here is my validation and attempt to send the string to the php script.
function validateForm()
{
var x=document.forms["subform"]["school"].value;
var y=document.forms["subform"]["confession"].value;
if (x==null || x=="" || y==null || y=="")
{
alert("Please complete the form before submitting your confession.");
return false;
}
if(x=="CWU"){
$.post('test3.php', $("images/colleges/cwu.png").serialize(), function(data) {
$('#content').html(data);});
}
}
Here is the php script which I am attempting to submit to the image column in the test table.
<?php
// Create connection
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO test (image)
VALUE
('$_POST[image]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "image added";
?>
If you want to prevent a form from submitting on the client-side before it can even get to the server, you could do something like this:
$('#myform').submit(function(e) {
var input = $('#myform input').val();
if(input == '') {
//won't allow the form to submit
e.preventDefault();
} else {
//do something
}
});
If you want to implement it on the server-side with PHP, you could do something like this:
$input = $_POST['val'];
if(!empty($input)) {
//carry out the request
} else {
echo "You did not fill out the form!"
}
If you went with the server-side option, it would probably be best implemented in an AJAX environment so that the user doesn't even leave the page when the form is submitted, and then get an error message. This would disrupt the flow a little bit.
Related
I have an issue with php and javascript included.
Sedning form from data index.php to edit.php
this is my edit.php file:
<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>
<?php
session_start();
// connect to database
include("connection.php");
// update records
if (isset($_POST['update'])) {
$chk=$_POST['chk'];
$manyids=implode(",",$chk);
//$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$user = $_POST['user'];
// if time is NULL ask if you are sure
if ($time == "") {
echo "<script type='text/JavaScript'>
ConfirmNull();
</script>";
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
else {
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
}
?>
Right now if the value time variable is NULL it should run javascript with the question: are you sure?
If YES continue with SQL and update the db.
If Cancell stop the php code and run windows.history.back and do NOT run SQL.
Unfortunately its updating the db when i hit Cancel.
PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.
So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:
document.querySelector('#myForm').addEventListener('submit', evt => {
if (evt.target.querySelector('[name="time"]').value === '') {
if (!confirm('Are you sure?')) evt.preventDefault();
}
});
And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.
Hi i am trying to implement notifications when certain event happens in PHP. Suppose a user is changing its password and after the form is submitted the action takes it to update.php, if the password was succesfully changed the page will redirect to change.php?err=1 where 1 has a noty notification which shows password changed succesfully. If there was some problem it redirects to change.php?err=2.
The code for updating password in update.php :-
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
header('Location: ../change.php?err=1');
}
else {
header('Location: ../change.php?err=2');
}
The below code for is for showing messages in change.php.
if(isset($_GET['err']))
{
$error_id = $_GET['err'];
if ($error_id == 1) {
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
else
if ($error_id == 2) {
echo "<script> noty({text: 'Something went wrong',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
Now if the page is refereshed it will show the message again and again. I want to show the message only when it is redirected not on refreshes.
I thought of a workaround using sessions like this:-
if ($error_id == 1) {
if(!isset($_SESSION['notify'])) {
$_SESSION['notify'] = TRUE;
echo "<script> noty({text: 'Password Changed Successfully',layout: 'topRight',timeout: 2500,closeWith: ['click', 'hover'],type: 'success'});</script>";
}
}
But it stops the message on refreshes but it doesn't show when page is redirected.
I am just starting to learn php so please let me know what I am doing wrong or what else could be better way to solving this problem. Any help is highly appreciated.
Well in addition to
if(isset($_GET['err'])){}
you can add:
if(isset($_GET['err']) && $_SERVER['HTTP_REFERER'] == YOUR_PREV_PAGE){}
In your case it is update.php
This kind of functionality typically works best when you use an ajax call, that means: without refreshing the page.
You could call update.php in the background (see docs of the link pasted above), and decide in the callback of that ajax function what notification to show, based on the response of your update.php script.
EDIT: simple example
$.ajax({
url: "/update-password.php",
data: {
user: "some-user",
pass: "new-pass"
}
}).done(function(response) {
// Show notification, decide on contents based on response
});
Use SESSION instead of GET for error messages. Set an error at the time it's detected, prior to your header() call:
session_start();
$sql="UPDATE user_credentials SET password=? WHERE id=?";
$stmt = $result->prepare($sql);
$stmt->bind_param("si", $hash,$id);
if($stmt->execute()) {
$_SESSION['error'] = "You password was changed.";
header('Location: ../change.php');
}
else {
$_SESSION['error'] = "We could not change your password.";
header('Location: ../change.php');
}
In change.php (and in any other page were a message might be set), do something similar to this:
session_start();
if (strlen($_SESSION['error'])) {
echo $_SESSION['error'];
$_SESSION['error'] = false;
}
I'm trying to load a response from the php onto the same page. My Client side html looks like this.
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
// ]]></script>
</p>
<div id="responseDiv"> </div>
<form action="AddClient.php" onsubmit="sendForm()">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label> <span>Client Name :</span> <input id="ClientName" type="text" name="ClientName" /> </label> <span> </span> <input class="button" type="Submit" value="Send" />
</form>
My Server side php looks like this:
<?php
$dbhost='127.0.0.1';
$dbuser='name';
$dbpass='password';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$client=$_REQUEST["ClientName"];
$retval=mysqli_query($conn,"INSERT into client (clientid,clientname) VALUES (NULL,'$client')");
if(!$retval)
{
die('Could not add client:'.mysql_error());
}
$display_string="<h1>Client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
Unfortunately not only is the response being shown in anew html page, Its not accepting any name typed in the form. When I check the sql table the Column has a blank entry under it. I have not been able to figure out where I'm going wrong. Any help would be really appreciated.
All right. Your code have some room for improvement, but it's not an endless thing.
I saw somebody mention sanitization and validation. Alright, we got that. We can go in details here
This is how I will restructure your code using some improvements made by Samuel Cook (thank you!) and added a lot more.
index.html
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = {clientName: $('#clientName').val()}
$.post("AddClient.php", dataSend, function(data) {
$('#responseDiv').html(data);
});
return false;
}
//]]>
</script>
</p>
<div id="responseDiv"></div>
<form action="AddClient.php" onsubmit="sendForm(); return false;">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label><span>Client Name :</span><input id="clientName" type="text" name="clientName"/><span></span><input type="submit" class="button" value="Send"></label>
</form>
Notice change in an input id and input name - it's now start with a lower case and now clientName instead of ClientName. It's look a little bit polished to my aesthetic eye.
You should take note on onsubmit attribute, especially return false. Because you don't prevent default form behavior you get a redirect, and in my case and probably your too, I've got two entries in my table with a empty field for one.
Nice. Let's go to server-side.
addClient.php
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'dbname';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
$client=$_REQUEST["clientName"];
$client = filter_var($client, FILTER_SANITIZE_STRING);
if (isset($client)) {
$stmt = $conn->prepare("INSERT into client(clientid, clientname) VALUES (NULL, ?)");
$stmt->bind_param('s', $client);
$stmt->execute();
}
if (!$stmt) {
die('Could not add client:' . $conn->error);
}
$display_string = "<h1>Client $client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
That is going on here. We are using PHP filters to sanitize our incoming from somewhere string.
Next, we check if that variable $client even exist (you remember that twice sended form xhr? Double security check!)
Here comes a fun part - to protect our selves even more, we start using prepared mySQL statements. There is no way someone could SQL inject you somehow.
And just check for any errors and display it. Here you go. I've tested it on my machine, so it works.
Forms default behavior is to redirect to the page given in the action attribute (and if it's empty, it refreshes the current page). If you want it to make a request without redirecting to another page, you need to use Javascript to intercept the request.
Here's an example in jQuery:
$('form').on('submit', function(e) {
e.preventDefault(); // This stops the form from doing it's normal behavior
var formData = $(this).serializeArray(); // https://api.jquery.com/serializeArray/
// http://api.jquery.com/jquery.ajax/
$.ajax($(this).attr('action'), {
data: formData,
success: function() {
// Show something on success response (200)
}, error: function() {
// Show something on error response
}, complete: function() {
// success or error is done
}
});
}
Would recommend having a beforeSend state where the user can't hit the submit button more than once (spinner, disabled button, etc.).
First off, you have a syntax error on your sendForm function. It's missing the closing bracket:
function sendForm() {
//...
}
Next, You need to stop the form from submitting to a new page. Using your onsubmit function you can stop this. In order to do so, return false in your function:
function sendForm() {
//...
return false;
}
Next, you aren't actually sending any POST data to your PHP page. Your second argument of your .post method shouldn't be a query string, but rather an object (I've commented out your line of code):
function sendForm() {
var dataSend = {ClientName:$("#ClientName").val()}
//var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
return false;
}
Lastly, you have got to sanitize your data before you insert it into a database. You're leaving yourself open to a lot of vulnerabilities by not properly escaping your data.
You're almost there, your code just need a few tweaks!
I have a contact form on my website and I'm trying to implement send to email functionality when the user enters information and clicks submit. So, ideally the information in the contact form should be emailed to me after submit. What I'm trying to implement uses jQuery, AJAX, and a PHP mailer script I got from the tutorial located here: http://blog.teamtreehouse.com/create-ajax-contact-form
The problem is when I click Submit, nothing happens, nothing is redirected stating there is an error or telling me it's successful. Only thing to happen is the form fields are cleared. I read in the comments on that site a certain version of PHP is required for the mailer script, but I'm not too experienced with PHP and back-end development. I know something's missing, just not sure what. Seems like some communication is missing and I'm not getting any javascript errors. All of the id and name attributes match in my .html, .js and .php files. Files are also uploaded in Bluehost (currently where site is hosted). Do I need to install a new PHP version somewhere in Bluehost? Any help is appreciated. Thanks!
$(document).ready(function(e) {
//e.preventDefault();
$("button").click(function(e) {
var ajax = {
isSubmitting: false,
send: function() {
if(ajax.isSubmitting == false) {
ajax.isSubmitting = true;
var userName = $("input [name=contact-name]");
var userEmail = $("input [name=contact-email]");
var userWebsite = $("input [name=contact-website]");
var userMessage = $("input [name=contact-message]");
if(userName === "" || userEmail === "" || userWebsite === "" || userMessage === "") {
alert("Please fill out all required fields.");
}
else {
$.post("mailer3.php", {
name: userName,
email: userEmail,
website: userWebsite,
message: userMessage
}, function(data) {
ajax.isSubmitting = false;
});
}
}
else alert("Send only 1 email at a time.");
}
}
});
});
PHP
<?php
//PHP Mailer Script
if(count($_POST) > 0) {
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$message = $_POST['message'];
$header = "Content-Type: text/html\r\nReply-To:: $email\r\nFrom: $name <$email>";
$body =
#"Email sent from ".$_SERVER['REMOTE_ADDR']." at ".date("d/m/Y H:i",time())."<br />
<hr />
$message
<hr />
Email end";
if(mail("andrew#ajcwebcreations.com", "You have a new message.", $message, $header)) {
die("true");
} else {
die("Error sending message.");
}
}
?>
Andrew
Started over from scratch and got email to send, but input isn't included in the email only the subject. Maybe going to post another question for that issue if I can't figure it out. Thanks to all those who took the time to add input!
I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];