I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.
Related
I'm trying to make a "sign in status" thing.
Here is a summary of what is happening.
User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.
So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...
I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.
I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.
Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.
HTML:
<label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
<label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
<div id = "xx2"></div>
jQuery:
$(document).ready(function(){
$("#button2").click(function(){
var name1=$("#name1").val();
var pass1=$("#pass1").val();
var key = "signIn";
$.ajax({
url:'rpc.php',
method:'POST',
data:{
name1:name1,
pass1:pass1,
key:key
},
success:function(data){
if(data === '1')
{
document.getElementById('xx1').innerHTML = "Status: Online";
}
document.getElementById('xx2').innerHTML = data;
//var p = data;
}
});
});
});
(xx2 is updating by the way)
Lastly, relevant bits of my rpc.php:
else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];
if($name1 !== "" && $pass1 !== "")
{
$sql = "SELECT * FROM whatever";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($name1 === $row["username"])
{
$UNTrue = true;
if (password_verify($pass1, $row['password'])) {
$PassTrue = true;
}
}
}
} else {
//echo "0 results";
}
if($UNTrue === true && $PassTrue === true)
{
echo "1";
$conn->close();
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";
$conn->close();
}
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";
$conn->close();
}
}
So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".
I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.
The other option would be to figure out how to use PHP global variables without file inclusion.
Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.
I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>
use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**
I have here a register HTML form with some elements. I need to validate the elements on server side and client side and I will explain why. For example, in HTML form I have:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
User name:<input type="text" name="user_name"/><br/>
Email:<input type="text" name="user_email"/><br/>
Password:<input type="text" name="user_password"/><br/>
</form>
I use PHP to check if the email and user already exists in the database. And I can use PHP to identify if the input fields are empty too.
if (isset($_POST['submit']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
$exists = "";
$sql = "SELECT user_name from users WHERE user_name = '{$user_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "u";
}
$sql = "SELECT user_email from users WHERE user_email = '{$user_email}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "e";
}
if (empty($user_name) || empty($user_email) || empty($user_password))
{
echo "<script>alert('Please fill all input fields to register!');</script>";
}
else if($exists == "u")
{
echo "<script>alert('This user is already registered in our system.');</script>";
}
else if($exists == "e")
{
echo "<script>alert('This email is already registered in our system.');</script>";
}
else if($exists == "ue")
{
echo "<script>alert('This user and this email are already registered in our system.');</script>";
}
else
{
//Here insert the values in database
}
}
Looks perfect, except for one thing: when I click submit the page is refreshed and all the input fields values are cleaned. This is bad because the user will have to enter all informations again because something was wrong. I know that the reason for this is because I am validating the form after sending it with PHP. To overcome this problem I need to validate the fields before sending the form, logically using JavaScript in the client side. But how about the check in the database? I will need to use PHP for that. If I did not have to check the database I could use JavaScript only. I would have to mix the validations with JavaScript and PHP, I think for that I should use AJAX, but do not know how.
Personally I would do the check at the client level (javascript) not in php but hey if you insists try this
if ($_POST["password_user"] != $_POST["confirm_password"])
echo "<script>alert('The entered passwords doesn't match. Try again.');
document.getElementByID('inputPassword').value = $_POST['password_user'];
document.getElementByID('inputConfirmPassword').value = $_POST['confirm_password'];
</script>";
Also update your HTML input to have ids
Password:<font color="red">*</font>
<input id="inputPassword" type="password" name="password_user"/><br/>
Confirm password:<font color="red">*</font>
<input id="inputConfirmPassword" type="password" name="confirm_password"/><br/>
Edit:
Added good AJAX tutorial:
without JQuery
with JQuery (I personally find this easier to use)
Edit2:
Sample code for PHP (server side) that returns a JSON to be fed back to the client (javascript)
<?php
$canLogin = false;
$responseArray = array();
// your logic here
// ....
if ($canLogin)
{
$responseArray["status"] = "Success";
} else
{
//Use the appropriate HTTP header (default 200), this is sometimes missed by developers
http_response_code(404);
$responseArray["status"] = "Error";
}
return json_encode($responseArray);
?>
I'm trying to create a player edit system for an admin section of a football website.
The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
coaches.php form
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input name="thisID" type="hidden" value="<?php echo $id; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
coaches.php js function
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").change(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
As the js above shows, the player list is handled via a separate page with a query on it as follows:
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coachplayer.php SQL query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
$targetU = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the player
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE id='$targetU' LIMIT 1");
$playerCount = mysql_num_rows($sql); // count the output amount
if ($playerCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$username = $row["username"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$coach = $row["coach"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
$attend = $row["attend"];
}
} else {
echo "Player doesn't exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
As I'm sure you can tell, I'm not too great of a coder, so it's very possible that it's a simply var that needs changing but any ideas where I have gone wrong will be much appreciated.
Thank you in advance.
You are using a form with post method. And the action URL seems quite different
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
Change it to
<form id="form1" name="form1" method="post" action="coachplayer.php">
and in coachplayer.php. Use
isset($_POST['thisID']
Ok, I admit this is not an answer to your question BUT, to be honest there is no such thing as 'your question' - there are contents of four files each of them with their own problems, and an implicit request to grock all of those 4 files and tell you what does not work and how it should be made to work.
Having said that:
Divide and conquer. Make sure your first script does exactly what needs to be done. Then second, then 3rd and only then 4th.
Use tools: For javascript - Dev Tools or Firebug. For queries - MySQL Workbench
When testing JS use console (here you can try out your js code interactively.
) and source tabs - there you can set breakpoints and follow execution line by line. Look at network tab - there you can see request (headers) and responses.
When debugging PHP comment out all your code and use var_dump every step of the way. I use PHP Storm so that i can debug PHP line by line real time.
And better ask questions that can be described with the least lines of code
PS. You can simulate GET requests by typing url in browser - that way you know whether your server side works or not without relying on unreliable JS
Just a Quick look, but your sql Statement seems wrong. Your sql query will search for the Player with the id '$targetU'. Make sure to enter the variable correctly
i have created a signup form which is validated by both javascript and php.Whenever any javascript form validation error occur such as username is required,it is displayed beside the form,But when any php validation error occur such as username already exist,it is displayed on another link.How can i display php validation errors beside the form?
<?php
include('configdb.php');
if(isset($_POST['submit']))
{
checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$sql1 = "SELECT username FROM users WHERE username = '$usercheck'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
//if the name exists it gives an error
if (mysqli_num_rows($result1) != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
}
Another option if you don't want to use ajax. It can be done with php but user need to reload the page to see error.
To do this, html form code and php validation code must be placed at the same file.
<?php
$error = false;
if(isset($_POST['submit'])){
// your validation
// if something wrong
$error = true;
}
?>
<form action="validation_checking.php" method="post">
<?php
if($error)
{ echo '<p style="color:red;">Sorry, the username '.$_POST['username'].' is already in use.</p>'; }
?>
<input type="text" name="username">
<input type="submit" value="submit">
</form>
You must use ajax to execute php functions without refreshing the page.
Read this