i have this php code in my form. I used pdo to get into mysql database and insert data. A simple form where use enters his name, email, comments, and a checkbox. I use this in jquery mobile environment.
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbName = 'database';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec('SET NAMES "utf8"');
}
catch(PDOException $e)
{
echo "Sorry, you are experiencing server Error: ".$e->getMessage();
exit();
}
if(isset($_POST['sendEmail']))
{
try
{
$senderName = $_POST['sendName'];
$senderEmail = $_POST['sendEmail'];
$comments = $_POST['comments'];
if (isset($_POST['offer'])) {
$offer = 1;
} else {
$offer = 0;
}
$dateTimeSent = date('Y-m-d H:i:s');
$q= "INSERT INTO comments(sendName, sendEmail, comments, offer, dateTimeSent) VALUES (:sendName, :sendEmail, :comments, :offer, :dateTimeSent);";
$query = $dbh ->prepare($q);
$results = $query->execute(array(
":senderName"=>$sendName,
":senderEmail"=>$sendEmail,
":comments"=>$comments,
":dateTimeSent"=>$dateTimeSent,
":offer"=>$offer,
));
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
include 'error.html.php';
exit();
}
exit();
}
?>
This is the form I use:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" name="comments" id="comments">
<div data-role="fieldcontain">
<label for="sendName">From: </label>
<input type="text" name="sendName" class="validate[required"] id="sendName" data-clear-btn="true" placeholder="Enter name" required >
</div>
<div data-role="fieldcontain">
<label for="sendEmail">Email: </label>
<input type="email" name="sendEmail" id="sendEmail" class="validate[required,custom[email]]" data-clear-btn="true" placeholder="valid_email#true.com" required >
</div>
<label for="comments"></label>
<textarea name="comments" id="comments" value="comments"></textarea>
<label for="offer">
<label for="offer">
<input name="offer" type="checkbox" id="offercheckbox">Please check</label>
</label>
<input type="button" name="Send Email" value="Submit" id="suggestSubmit" onclick="submitForm()">
</form>
My problem is I am trying to figure out how to clear the form fields after a successful submission. I found an option of using Jquery onclick function. I inserted this code before the end of form tag:
<script>
function submitForm() {
$('form[name="comments"]').submit();
$('input[type="email"], textarea').val('');
$('input[type="text"], textarea').val('');
}
</script>
However, if the form was submitted but failed in the jquery validation, all the fields will been cleared even if the submission failed due to but not limited to form validation. So the user when fixing his errors has to reenter all data in all the form fields again. Not good.
I checked the other answers here and other online sources, but i cant seem to make it work.
What`s is the best approach in clearing form fields after a successful submission, if I use PHP-PDO in jquery mobile?
PS. I am a newbie. Thanks.
After a successful submission do http redirect to the form page using header function, this is a pretty new request which should view forms elements in the page with empty status, just like the user is visiting this page for the first time.
It would also be nice to view a success message for the user when opening this page in order to get the sense that his previous request has been processed successfully.
Related
i'm have a form that's posting to another page. But i'm trying to stay on the same page if the fields are null and display all the error messages instead of going into my action page. Is there a way around this? i have tried using javascript to stop the form from submitting however it is not displaying the error messages. I want to know if this do-able using only php? I know i could just put everything in a page but i'm curious which way is more efficient or how it's suppose to be done? thanks a million
register.php
<?php include 'formCheck.php'; ?>
<form method="post" action="add.php">
<div class="textbox">
<label for="uname">Username:</label>
<span class="error">* <?php echo $uerror;?></span>
<input type="text" name="username" placeholder="Username">
</div>
add.php
<?php
require_once "db.php";
if ( !empty($_POST['username'])) {
$u = mysqli_real_escape_string($db, $_POST['username']);
$sql= "INSERT INTO users (username) VALUES ('$u')";
echo "<pre>\n$sql\n</pre>\n";
mysqli_query($db,$sql);
echo 'Success -Continue...';
return;
}
formCheck.php
<?php
$uerror = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$uerror = "Username is required";
}
}
?>
You can use jQuery to help you with this task.
$( "form" ).submit(function( event ) {
event.preventDefault(); //prevents from reloading
// your stuff
return false;
});
I am trying to verify the user's information against my database without leaving the page, and only if the information is correct should it leave the page and route the user to the user portal. The PHP works fine, it checks the information, and if correct routes the user to the portal, and if false it routes to an empty page.
What I'm trying to do is to intercept the submit, verify it against the database, output an error message if false, and route the user if correct.
I think the error I'm facing is how to get the PHP to somehow "signal" to the jQuery that it's false
I've created a submit handler, that stops the form from submitting, then serializes it and sends it to checkLogin.php, but I get no results after that.
I haven't sent the user anywhere if the info is correct, so it's expected that nothing would happen if the username and password are correct
THIS IS checkLogin.php
- DB is replaced with the actual database that connects, I'm not hosting on localhost, so the info is private
<?php
$link = mysqli_connect('DB', 'DB', 'DB', 'DB'); //Database Connection
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$username = mysqli_real_escape_string($link, $_POST['username']); //Retrieving the username
$password = mysqli_real_escape_string($link, $_POST['password']); //Retrieving the password
$user_sql = "SELECT username FROM login WHERE username = '$username'"; //Setting the SQL query
$user_check = mysqli_query($link, $user_sql); //Putting the result of the query (^) into a variable
if ($user_check) {
$test = "THIS WAS A SUCCESS";
} else {
$test = "THIS WAS A FAILURE";
}
?>
This is the function from login.js - the function is called after the user clicks submit
function checkLogin() {
$("#login_form").submit(function(event) { //Submit Handler
var post = $.post("checkLogin.php", $form.serialize());
post.done(function() { //When the function is successfully submitted
});
//$("#login_form").submit(); //Submit the form (blocked for now)
});
}
login.html - The form
<form action="login.php" method="post" name="login_form" id="login_form">
<div class="loginTitle">Client Login</div>
<div class="loginLabel">Username: <span id="userError"><?php echo $test ?></span></div>
<input type="text" name="username" class="loginBox" id="userName">
<div class="loginLabel">Password: <span id="passError"></span></div>
<input type="password" name="password" class="loginBox" id="passWord">
<br>
<input type="checkbox" name="rememberMe" value="rememberMe" id="remMe">Remember me for next time
<br>
<input type="submit" value="Login" name="submit" id="submit">
</form>
login.html - at the top
<?php
include ("checkLogin.php");
?>
Expected: It should say "This was a failure" next to the form label when I enter the wrong username
Actual: Nothing
I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>
I'm trying to get multiple checked checkbox value data added to mysql with php without reloading the form page and show confirmation message in div on form page. At the moment, showing on div works but data is not being sent.
I already have done another similar one which I had almost the same code that had the input as text area so I changed that part and it works but the this one is not working. Could anyone give me help here?
form is in vote.php:
<html>
<form action="vote_received.php" method="post" target="" id="vote-submit">
<input type="hidden" name="recieved-date" id="todayDate" />
<input type="hidden" name="user-occup" id="user-occup" value="<?php $_SESSION['occupation']; ?>" />
<input type="checkbox" name="voting[]" value="How might we improve driver facilities such as lunch rooms or break rooms?" id="voting_1">
<label for="voting_1">How might we improve driver facilities such as lunch rooms or break rooms?</label>
<input type="checkbox" name="voting[]" value="How might be increase driver security at night time?" id="voting_2">
<label for="voting_2">How might be increase driver security at night time?</label>
<input type="checkbox" name="voting[]" value="How might we change the on-call communication with management?" id="voting_3">
<label for="voting_3">How might we change the on-call communication with management?</label>
<input type="checkbox" name="voting[]" value="How might we enhance the passenger conflict management system?" id="voting_4">
<label for="voting_4">How might we enhance the passenger conflict management system?</label>
<br><br>
<input type="submit" name="submit" value="Submit" class="btn align-right"></form>
<script>
$("#vote-submit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = $messages.val(),
url = $form.attr('action');
var posting = $.post(url, { submission : message_value});
posting.done(function(data) {
/* Put the results in a div */
$("#vote_success").html('<h2>THANK YOU!</h2><p>Thank you for your voting. Meeting invitations will be send out on December 7th, 2017.');
/* Hide form */
$form.hide();
});
});
</script>
</html>
the vote_received.php is:
<?php
session_start();
if(isset($_POST['vote-submit'])) {
$voteArray=$_POST['voting'];
$conn = mysqli_connect($servername, $username, $password, $database);
if(is_null($voteArray)) {
echo("<p>You didn't select any topic.</p>\n");
} else {
$N = count($voteArray);
for($i=0; $i < $N; $i++) {
$var1 = $voteArray[$i];
$jobTitle = $_SESSION['occupation'];
$sql = "INSERT INTO vote_response (occupation, voting,
created) VALUES('$jobTitle', '$var1', now())";
$success = mysqli_query($conn, $sql);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $var1;
$conn->close();
}
}
}
?>
Thank you very much!
try to change this part of your code
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = [],
url = $form.attr('action');
$.each($messages, function(idx, val){
message_value.push($(val).val());
});
var posting = $.post(url, { submission : message_value});
on further reading of your code, try to change this part of you code also:
if(isset($_POST['submission'])) {
$voteArray=$_POST['submission'];
First,this is my AJAX code:
<script>
function ajaxInsert() {
var xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("select").innerHTML = xmlhttp.responseText
}
}
var user = document.getElementById("user").value
var pwd = document.getElementById("pwd").value
var email = document.getElementById("email").value
var str = "user=" + user + "&pwd=" + pwd + "&email=" + email
// document.write(str)
xmlhttp.open("post", "getconnectforxmlhttp.php", true)
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded")
xmlhttp.send(str)
}
and then,my form:
<form method="post" id="insertform">
<label for="user">用户名</label><input type="text" id="user" name="user">
<label for="pwd">密码</label><input type="password" id="pwd" name="pwd">
<label for="email">邮箱</label><input type="email" id="email" name="email">
</form>
<button form="insertform" onclick="ajaxInsert()">提交</button>
<div id="select"></div>
and last,my php code in the getconnectforxmlhttp.php file:
<?php
$pdo = new PDO("mysql:host=localhost; dbname=db_test", "root", "");
if (isset($_POST)) {
$values = "'".implode("', '", array_values($_POST))."'";
}
$str = "";
try {
$resp = $pdo->prepare("INSERT INTO user (user, pwd, email) VALUES ($values)");
$resp->execute();
} catch (Exception $e) {
$str .= "Error".$e->getMessage()."<br>";
}
if ($pdo->lastInsertId()) {
try {
$res = $pdo->prepare("SELECT * FROM user");
$res->execute();
} catch (Exception $e) {
$str .= "Error".$e->getMessage()."<br>";
}
$result = $res->fetchAll(PDO::FETCH_ASSOC);
for ($i=0; $i < count($result); ++$i) {
$str .= $result[$i]["id"]." ".$result[$i]["user"]." "
.$result[$i]["pwd"]." ".$result[$i]["email"]."<br>";
}
echo $str;
} else {
$str .= "插入失败";
echo $str;
}
?>
What it do is insert a new row into my table user in the local database,and then show them all between the div tag.but when I run this code,the insert statement successes,and the result(between the div tag) shows a second,yes,it do shows,but strangely,then it's gone,disappeared.Now I know how to do it right,simply delete the form attribute in the start button tag,and change the value of id of the div tag into something else,like:
<button onclick="ajaxInsert()">提交</button>
<div id="sel"></div>
also change AJAX code a little like document.getElementById("sel").innerHTML = xmlhttp.responseText,but with a little problem:I don't know what happened,what's the problem of the form I wrote in the first place,what the changes solve the problem?
I belive you are asking why you page will refresh when you click the button instead of running your javascript. This is probably because the button is linked to the form with its form attribute. This isn't the standard way to submit a form.
A HTML form requires a action and method attribute to submit. Without an action attribute the form will default to submit to the same page, which would explain a page refresh.
Although you intend for your form to submit using AJAX, What happens if your JavaScript breaks? What happens if your user doesn't have JavaScript enabled? In both situations your form can not submit.
Also, a HTML form is submitted using a input of type submit. This means you form may look like this;
<form method="post" action="getconnectforxmlhttp.php" onsubmit="event.preventDefault(); ajaxInsert();" id="insertform">
<label for="user">用户名</label><input type="text" id="user" name="user">
<label for="pwd">密码</label><input type="password" id="pwd" name="pwd">
<label for="email">邮箱</label><input type="email" id="email" name="email">
<input type="hidden" name="return" value="html">
<input type="submit" value="提交">
</form>
<div id="select"></div>
If this form submits without AJAX then it will submit all of its data to getconnectforxmlhttp.php. The input <input type="hidden" name="return" value="html"> will allow you to know that there is no JavaScript and the PHP should return a HTML page to display the data.
Otherwise your AJAX submits to the PHP file without the hidden input. In this case you PHP file can return just the data.
For users with JavaScript enabled the form attribute onsubmit will be used;
onsubmit="event.preventDefault(); ajaxInsert();"
This will first stop the form submitting normally, and then call your function to submit the form using AJAX.
This aproach towards JavaScript is called progressive enhancement, it allows your system to work for everyone but work better where posible. This is favoured rather than to make it not work for everyone but work better for some people