I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.
Related
I have a modifypassword form that modifys the password in a flat file for a user.( I know its not safe etc. ).
So the thing is: whenever I click on modify password on my website, I get a prompt that asked to enter a new password. All fine, after that it will submit the form. But I cannot get the variable somehow that is typed in. I want to $_GET['newpw'] so I can use it to adjust my flat file.
So I have a form like this:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
this is the modifyPassword function:
<script type="text/javascript">
function modifyPassword() {
var newpw=prompt("Enter a new password");
if(newpw !== null) {
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw},
success: function(data) {
console.log(data);
}
});
}
}
</script>
And when the form is actually submitted I want to get the value from what is typed in like this:
echo $_GET['data'];
This is all in the same file.
The output of $_GET['data'] does not show anything.
The rest just works fine when I choose a static password like: "test". It will update my flat file, but I want to get the user input to change the password.
Can someone tell me what i am doing wrong?
I think the base problem may be, that you have event handler onsubmit, but the form gets submited anyway. So the actual prompt has no chance to execute.
You should add return false; or manage the logic in modifyPassword() method.
For example this may help to stop form to submit:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(); return false;\">"
OR
If you want to submit the form in standard way, just to change the password, just change the input value.
Modify form: echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(this)\"><input type=hidden name=newpw />"
And then change the javascript:
<script type="text/javascript">
function modifyPassword(passForm)
{
var newpw = prompt("Enter a new password");
if (newpw !== null)
{
passForm.newpw.value = newpw;
}
}
</script>
Then you should have the value in php in $_GET['newpw'].
Your current PHP code:
}elseif (isset($_GET['Modify'])){ echo $_GET['data'];
But according to the Ajax request code, you don't send a Modify parameter so the $_GET['Modify'] isn't set and therefore the condition returns false and never reach to the echo $_GET['data'] part.
You need to add another parameter to the data as in the following:
JS
<script type="text/javascript">
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {action: 'modifypass', data: newpw}, //Added another parameter.
success: function(data)
{
console.log(data);
}
});
}}
</script>
PHP
elseif (isset($_GET['action']) && $_GET['action'] == "modifypass"){
echo $_GET['data'];
This question already has answers here:
When should I return true/false to AJAX and when should I echo "true"/"false"
(4 answers)
Closed 6 years ago.
I am trying to create a Ajax functions that made a decision based on a return var from PHP. The main issue I have is the return var will display correctly when I print it to an html class, but the decision within ajax still produces the same result of false.
Below is the PHP form:
<form class="LogInForm" method="post" action="Auth.php" >
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address" value="<?php echo $_SESSION['email'];?>">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pw" placeholder="password">
</div>
<button type="submit" class="btn btn-default btn-block">Submit</button>
And below is the jquery script:
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
if(data == 1){;
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(){
}
});
});
The PHP Function:
function Auth()
{
//start session and compture login info
$pass = md5($_POST['pw']);
$user = $_POST['email'];
//connect to DB
$conn = Connect();
//Select all queries
$select = "SELECT Email, Password FROM customers WHERE Email ='".$user."' AND Password = '".$pass."'";
$results = $conn->query($select);
//search in db for user and passwrod, also store quires in var to store in sessions.
if ($results->num_rows > 0) {
$bool = true;
}
else{
$bool= false;
}
echo $bool;
}
What happens is if I don't put in the right password if alerts me False and under the submit button tell me what the data is (which is null). When I put in the correct password, it still alerts me False but the data displays under the submit button as 1.
Also note when I bypass the Ajax function The PHP function works correctly.
Update
I was able to get this working. All i did was move the php file Auth.php to another directory and it seem to fixed the issue. I know it wasn't a file path issue. I thank you all for your time and thank you for answering and pointing me in the right direction with security vulnerabilities.
Javascript == is false if the values are of different types. I suspect the value you're getting back through AJAX is being read as the string "1" instead of the integer 1 (or the boolean TRUE). Try changing your comparison to:
if(data == '1')...
i have tested this, its working correct
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
//remember the returned value is a type string if not changed or maybe it a raw integer from php
if(parseInt(data.trim().replace(/\D*/g,'')) == 1){
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(e){
//check the logged error for more details
console.log(e)
}
});
});
I'm using $_SERVER['PHP_SELF'] to run a function because of the way it's included and called within my plugin page I can't directly call the functions.php file, so what I'm trying to do now is work on the registration script, the problem is my returns can't be utlized the way I would like. For instance.
public function CheckUserName() {
$query = <<<SQL
SELECT id
FROM {$this->tprefix}accounts
WHERE username = :posteduser
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':posteduser' => $_POST['username'],
));
if($resource->rowCount() == 0 ) {
//Self Continue to run checks
}
else {
echo "1";
}
}
is my check to make sure that a username isn't already taken, whereas two will be my response echoed if the email is already in use. My Ajax is
$(function() {
$("#register_").submit(function(event) {
event.preventDefault();
var username = $("#username").val();
if(username == "") { $("#unameerror").html("Username is Required"); }
$.ajax({
type: "POST",
url: $("#register_").attr("action"),
data: $("#register_").serialize(),
success: function(data) {
if(data==1) { alert("Username is taken. Please choose another!" };
if(data==2) { alert("Email already registered. Please select lost password
if you have forgotten your password" };
if(data==0) { alert("Account Created!") }; //0 is returned after all checks passed and scripts executed
},
error: function() {
alert("Something isn't right");
}
});
});
});
My issue is since it's running from PHP_SELF it's putting out all information(IE <html><title>reg script</title><body><form id = "reg"></form></body><html>
The best way I can think to put this is how can I parse all my data return to simply return the script code?
This worked for my framework. Since everything is included into the index.php file and then just pulled through variables as includes it's always the index.php file
which is currently
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once(dirname(__file__).'/config.php');
require_once(dirname(__file__).'/directives.php');
LoadClasses();
$Theme->Load(ACTIVETHEME);
I simply changed the bottom part to
if(isset($_POST['process'])) {
}
else {
$Theme->Load(ACTIVETHEME);
}
Now it has no problem loading my pages, but when I execute a form with process input ( IE <input type="hidden" name="process" id="process" value="register"> )
It now loads the page if no form is executed, but since I want all plugins to run through ajax it works great with that addition if a process was posted then it only returns the php scripts data.
I'm using this code to post a form using jquery ajax .
my problem is that i want to make php code to be like this:
if (isset($_POST[''])) {
// some code here
}
this is the javascript code:
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" )
$("div#status").html("Please enter your Email");
else
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
$("#myForm").submit( function() {
return false;
});
});
If you tested the code, and the php section works fine, but you can not get a response in jquery, then, you should check your php code(It should be like this):
if (isset($_POST[''])) {
$data = "";
// some code here to fill $data
echo $data; // this is the actual response to the jquery interface.
}
There are 6 b's in php file name but 7 b's in ajax url.
url: "bbbbbbb.php", <--- 7 b's
bbbbbb.php <--- 6 b's
Plus, along with success you should have error also so you'd see what the error is.
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
Despite a lack of actual question, here's a crack at an answer.
The first issue is that the javascript, while working, won't get to do the complete job it's supposed to do. The javascript code appears to want to prevent the form from being manually submitted via the submit event. You may want to reorganise the javascript to look like:
$("#myForm").submit( function() {
return false;
});
$("button#submit").click( function() {
if( $("#username").val() == "" || $("#password").val() == "" ) {
$("div#status").html("Please enter your Email");
} else {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(),function(data) {
$("div#status").html(data);
});
}
});
Additionally, you may want to look up usage of modern event watching in jquery, and the usage of .on(). i.e. $("#myForm").on("submit", function() {});. But that's not quite the point of this post.
As for the PHP code, let's infer you have the following HTML form:
<form action="login.php" id="myForm">
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
<button type="submit" id="submit" name="submit" value="submit">Submit</button>
</form>
<div id="status">Please provide username and password to login</div>
In login.php, you would have
if (!empty($_POST)) {
if (isset($_POST['submit']) && $_POST['submit'] == 'submit') {
// validate $_POST contains username and password
...
// sanitize username and password
$username = sanitize($_POST['username']);
$password = sanitize($_POST['password']);
// do my processing
// doLogin returns true for successful login, or message contain error string
$result = doLogin($_POST['username'], $_POST['password']);
if ($result === true) {
echo 'You have successfully logged in';
} else {
echo $result;
}
} else {
echo 'Unknown form action';
}
} else {
// do GET processing
}
With this, just echo the response you want to appear in the div#status.
I have found many AJAX scripts that do a live check on if the username exists in a MySQL database. For example, most will maybe show a green check image if it does not exist or a red x if it does already exist.
I am interested in a slightly different method for this form.
Users fill out a 10 question quiz and then are taken to a user registration form. I only want to insert the user's answers into the database if they complete the quiz.
Currently, if a user enters a username or email that already exists, they will receive an error on the next page and be told to be go back only to find that the form has been reset.
That is why I want the information validated all on the same page.
Upon clicking the submit button, a javascript function is called that verifies a few things such as if the user has entered a date of birth, has not left a form blank, if passwords match, etc.
It returns false if any of the criteria is not met so that the form does move to the next page unless all of the functions return true.
Here is what it looks like.
function checkForm() {
if (checkUser() && checkPassword() && checkMonth() && checkDay() && checkAddress() && checkYear()) {
document.getElementById("quizForm").method="post";
document.getElementById("quizForm").action="register.php";
}
else {
return false;
}
}
I am interested in creating a username/email check function that uses ajax to access a php page that searches the database and returns true or false to javascript on if the username/email exists in the database.
That way, I can just use the old javascript alert to say if a username/email exists and then return false so that the form is not submit.
This is an example of how I am writing the functions for this:
function checkPassword() {
var pass1 = document.getElementById("pass").value;
var pass2 = document.getElementById("c_pass").value;
var pass1l = pass1.length;
if (pass1l < 5) {
alert("Please create a password that is longer than 5 characters.");
return false;
}
else {
if (pass1 != pass2) {
alert("Your passwords do not match.");
return false;
}
else {
return true;
}
}
}
Can anyone point me in the right direction for this? I have been searching around but have not found anything that is this specific.
Thank you.
You could AJAX Post on change event of the <input> where the user enters the username. Consider the example below I quickly put together. It assumes you have the database table users with columns id and username. It also assumes you have a file check.php connecting to this database table with a MySQLi connection in the variable $mysqli. When the input changes, it will call check.php, with the only data being the username entered. Depending on the response, it will update <span id="info">.
HTML:
<input id="username" type="text" /><span id="info">Exists/Does not exist</span>
Javascript(jQuery):
$(function() {
$("#username").on("change", function() {
var data = "user="+$("#username").val();
$.ajax({
type: 'POST',
url: 'check.php',
data: data,
dataType: 'json',
success: function(r)
{
if(r=="1")
{
//Exists
$("#info").html("Username already exists");
}else{
//Doesn't exist
$("#info").html("Username available!");
}
}
});
});
});
PHP(check.php):
$user = $_POST['user'];
if($stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ?"))
{
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id);
$stmt->fetch();
if($stmt->num_rows>0)
{
echo "1";
}else{
echo "0";
}
}
I'm using similar functionality on my current project, and it works fine. Especially with local files as response time is improved!
(Reserved for typos, was in a rush-ish)
Hope this helped.