FIXED jQuery Validate + php check user exits - javascript

I am trying to add to a form, which is validated with jQuery validate, and a PHP script where I check if the user (usuario) exits. Each user has a different folder. To check if the user exits, I check if the folder exists then if exists, tell there is an error and I don't want to stop the form from being submitted. If not, I create the sub-folder with the username and create the folder.
Currently, I use the AJAX solution, but the PHP is not executed, and it won't print any echo on it.
I have been reading more about AJAX and about the remote attribute in jQuery validate but neither way I can get my functionality to work out.
With Ajax (or what I have understood as ajax)
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}
With remote
"usuario":{
required: true,
rangelength: [3, 10],
remote: {
url: "check-user.php",
type: "get",
data:{
usuarios: function(){
return $('#usuario').val();
}
}
}
}
My PHP
<?php
$user = $_REQUEST['usuario'];
$dir = "usuarios/$user";
if (!file_exists($dir)) {
echo 'true';
} else {
if(!mkdir($dir, 0777, true)) {
echo 'Fallo al crear las carpetas...'
}
$doc = new_xmldoc('1.0');
$root = $doc->add_root('historial');
$fp = #fopen('historial.xml','w');
if(!$fp) {
echo 'Fallo al crear historial.xml'
}
fwrite($fp,$doc->dumpmem());
fclose($fp);
echo 'true';
}
?>
Piece of my form (HTML)
<form id="register" action="index.php" method="post" onsubmit="return validateForm();">
<div class="elRegister"><label>Usuario:</label>
<input name="usuario" id="usuario" type="text" size="16"></div>
UPDATE:
Closing correctly the brackets i continue having problems.The rules goes fine but after filling correctly my form, when i press submit button it makes nothing. If something in my form is wrong it will display the error corrrectly.
My script will have the following structure:
<script type="text/javascript">
(function($, W, D) {
var validaForm = {};
validaForm.UTIL =
{
setupFormValidation: function()
{
//Reglas de validacion
$("#register").validate({
debug:true,
rules: {
},
messages: {
},
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}
});
}
}
$(D).ready(function($) {
validaForm.UTIL.setupFormValidation();
});
})(jQuery, window, document);
</script>
Thanks for everything and if you need more things of my code, simply ask.
FIXED
Finally i hve been able to fix this problem. I found the solution in here: YouTube
The solution was to use both, ajax and remote rule. With remote rule i check if the user exists and with the ajax i override the form submit and write another one instead which look like:
$("#register").submit(function() {
var valido = $("#register").valid();
if(valido){
var $inputs = $('#register :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
alert("Formulario valido");
$.get("crear_usuario.php",values);
}
else{
alert("Formulario no valido");
}
});
Thank you for your answers!

You are not properly closing submitHandler. Here is the fixed code.
submitHandler: function(form) {
var username = $(this).val();
$.post('check_user.php', {'usuario':username}, function(data) {
$("#user-result").html(data);
form.submit();
});
}

Related

How to check unique username before form submission

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.

Why Its not working: Jquery Ajax success data with PHP return variable [duplicate]

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)
}
});
});

passing login data from ajax to php script

Here is my script in the html page:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
I am trying to get the values from the html input boxes and then passing those values to the ajax code which passes it to the php script, which then validates the login id and password and echoes a message
The php script:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div where message should be printed:
<div id="status"></div>
When I run the code in the browser no errors are shown, but the code does not work and neither the message is displayed nor is the validation done.
My contribution:
In ajax requests I suggest you to end the php script, you can use a simple die(); for this. After this, you must to print the response, you can use numeric or string pattern to expose this like: 'success' or 'fail', also: 1 or 0.
Here is the same example with a new solution:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
Don't forget to filter data in php, never trust in your user!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();
i solved it by preventing it from performing the default function
i used e.preventDefault() it worked but i have a new problem now
the page to which the php script tries to redirect appears on the same login page how should i solve this now??
here is a screen shot of the same
Give this a try:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>
You must redirect with javascript, you are not actually going to the php page, you are just retrieving whatever is printed.
window.open(page,'_self')
rather than
header(...)

Return Single Response using PHP_SELF

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.

Use jScript / AJAX to call PHP script but ONLY if form has been submitted?

This is kind of a follow up to this question.
I have this code:
var chpass = function()
{
var pass1 = encodeURIComponent($("#pass1").val());
var pass2 = encodeURIComponent($("#pass2").val());
$.ajax(
{
type: "POST",
url: "lib_ajax/somescript.php",
data: "pass1="+ pass1+"&pass2="+ pass2,
success: function(msg_pass)
{
$("#status_pass").ajaxComplete(function(event, request, settings)
{
if(msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
});
}
});
}
$("#signup").ready(chpass);
$("#signup").change(chpass);
And in the php script:
$pass1 = trim($_POST['pass1']);
if(!isset($pass1)||empty($pass1)) die('empty pass1');
My problem is that I don't want the form to be validated with ready() the first time the page is loaded but every time the page is loaded after a submit.
I have tried to figure out how to set a default event for the handler and then use preventDefault but I've been completely unsuccessful so far.
Could part of the problem be that when the page is submitted some additional validation happens on the server and in some cases I use header('Location: ') to reload the page?
Any tips how I can work this out? Is there a way to change it to something like:
if ( FORM IS SUBMITED ) $("#signup").ready(chpass);
Or maybe:
if ( FORM IS SUBMITED && msg_pass == 'empty pass1')
{
$("#pass1").removeClass('green');
$("#pass1").addClass("red");
}
Can also add that I have tried to change ready() to submit() with no luck:
$("#signup").submit(chpass); // DO NOT WORK
I finally found a solution. Change the code:
$("#signup").ready(chpass);
to:
<?php if(isset($_POST['submit'])) { ?>$("#signup").ready(chpass);<?php } ?>
and that part of the jScript is left out unless the form is submitted!

Categories

Resources