JavaScript Username authentication - javascript

The following represent my registration link which lead to open a modal:
Register Here
The following represents the code for my modal dialog:
<div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" name="f2" id="regisform" method="post" onsubmit="return false;" role="form">
<div class="modal-header">
<h4>Registration<button class="close" data-dismiss="modal">×</button></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputusername3" class="col-sm-2 control-label">Username</label>
<div class="col-lg-8">
<input type="text" name="txtusername" class="form-control" id="inputusername3" placeholder="username">
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="submit" id="regisBtn" class="btn btn-primary" value="Registration">
<a class="btn btn-default" data-dismiss="modal">Cancel</a>
</div>
</form>
</div>
</div>
</div>
The below represent the JavaScript Code:
$(document).ready(function(){
$("#regisBtn").click(function(){
var username1=$("#inputusername3").val();
$.post("registercheck.php", {username:username1}, function(result){
if(result==='true')
alert("true");
else
alert("false");
});
});
});
The below represent my php code:
<?php
$username1=$_POST['username'];
$con= mysql_connect("localhost","root","");
mysql_select_db("onlineshop",$con);
$query1= mysql_query("select username from users where username=$username1",$con);
if(mysql_num_rows($query1)==1){
echo 'false';
}else{
mysql_query("insert into users(username)values ('".$username1."')",$con);
session_start();
$_SESSION['username']=$username1;
echo 'true';
}
There is error in mysqli_num_rows() shows that it expects parameter 1 to be resource, Boolean given in something like that
I dont knw why my code is not working. please help me with my code to check whether the username is exists or not?

You have 4 problems with your code. First, you are using mysql_* functions. Use mysqli_* instead, mysql_* is deprecated. Second, you are vulnerable to SQL injection. This is fixed below by using mysqli_real_escape_string. Consider using PDO instead. Third, your select query is malformed - any string in the query must be wrapped in single quotes. Fourth, in a couple of mysql_* function calls, your database link is the last parameter. It should always be the first parameter in the call.
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "onlineshop");
$clean_username1 = mysqli_real_escape_string($con, $_POST['username']);
$query1 = mysqli_query($con, "select username from users where username = '".$clean_username1."'");
if (mysqli_num_rows($query1) == 1){
echo 'false';
} else {
mysqli_query($con, "insert into users (username) values ('".$clean_username1."')");
session_start();
$_SESSION['username'] = $_POST['username'];
echo 'true';
}

Related

Preventing bootstrap modal from disappearing in case validation failure using PHP after submit button is clicked

My question is how do I stop modal from closing, on two occasions, when user clicks the sign up button:
if the inputs are invalid? and display PHP error message
inputs are valid and to display PHP success message for couple of seconds before closing modal?
for the first case if I reopen the modal I can see the validation error messages which are displayed by PHP.
I have checked this similar question but haven't figure it out how to do it in my case yet so any help will be much appreciated. I would like to fully understand what is going on and what I am doing.
So far after reading here and there I noticed that this can probably be achieved by:
JQuery / JavaScript to do the form validation and not to use PHP
some people suggested using iframe
Is there a way to use the PHP code below and display error / success messages from this code? or it has to be done via JQuery/JS?
My PHP with HTML code
<?php
ob_start();
include('header.php');
include_once("db files/db_connect.php");
if(isset($_SESSION['user_id'])) {
header("Location: index.php");
}
$error = false;
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$uname_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success_message = "Successfully Registered!";
} else {
$error_message = "Error in registering...Please try again later!";
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="registrationFormLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" >
<div class="modal-header">
<h5 class="modal-title" id="registrationFormLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- REGISTRATION FORM -->
<div class="container">
<div class="form-row">
<div class="col">
<form onsubmit="return validateForm()" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<legend>Sign Up</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($uname_error)) echo $uname_error; ?></span>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Password" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
<div class="form-group">
<label for="name">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
<div class="form-group text-center">
<input id="modalSubmit" type="submit" name="signup" value="Sign Up" class="btn btn-primary" formnovalidate />
</div>
</fieldset>
</form>
<span class="text-success"><?php if (isset($success_message)) { echo $success_message; } ?></span>
<span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></span>
</div><!-- / col -->
</div><!-- / form-row -->
<!-- already registered row -->
<div class="row">
<div class="col text-center">
Already Registered? Login Here
</div>
</div> <!-- / already registered row -->
</div><!-- / REGISTRATION FORM container-->
</div><!-- / Modal body div -->
</div>
</div>
</div><!-- / Modal -->
My modal opens when the user clicks the button on index page and here is the JQuery code
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
Add below PHP script after end of document (/html) before script tag
<?php
if ($error) {
echo '<script>$("#myModal").modal("show");</script>';
} else {
echo '<script>$("#myModal").modal("hide");</script>';
}
?>
Invalid:
You can stop the submit button from submitting if the inputs are invalid.
To stop submit use the code
$(':input[type="submit"]').prop('disabled', true);
To show modal
$("#myModal").modal('show');
To enable submit again, when modal is closed due to error, use the code
(You will want to enable it again so the user can try again)
$("#myModal").on('hidden.bs.modal', function (e) {
$(':input[type="submit"]').prop('disabled', false);
});
For the validation I would do it this way (add a success variable):
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success = 1;
} else {
$success = 2;
}
And then call it like this:
<?php if($success == 1){ ?>
<script>
$(document).ready(function() {
$("#yoursuccessmodal").modal('show');
});
</script> <?php } ?>
You can then choose to add a fade to it, or have the user click it away.
The modal will then show AFTER the submition has been sent.
This better work, as I have used it this way in my project as well and it works like a charm for me.

jquery .post can't pass the value into php for checking

I have a question in jquery - Post . when I input the email in the form, the js - jquery will pass the email into sendResetPasswordMail1.php to check email is valid or not.
but now, $.post("sendResetPasswordMail1.php",mail:email},function(resetPasswordMsg) can not work in js.
I can't find what wrong. Distress.
Could you help me please.
Many Thanks.
php
<!--reset Password Popup start-->
<div class="resetPasswordLayer" id="resetPassword" tabindex="-1">
<div class="resetPasswordLayerWall" id="resetPasswordLayerWall">
<button type="button" class="close resetPasswordCloseButton" aria-label="Close"><span aria-hidden="true">×</span></button>
<p><h3 class="layerTittle">Reset Password</h3></p>
<div class="row">
<!--<form class="form-horizontal" action="ResetPassword/sendResetPasswordMail.php" method="post" id="login-form">-->
<div class="form-horizontal form-group">
<div class="input-group">
<p><strong>User can retrieve the password through the mailbox</strong></p>
<!--<p><strong>Enter your registered e-mail, retrieve your password:</strong></p>-->
<p><input type="text" class="form-control" name="resetPasswordEmail" id="resetPasswordEmail" placeholder="Enter your registered e-mail, retrieve your password."><span id="chkresetPasswordMsg"></span></p>
</div>
</div>
<div class="form-group">
<div class="input-group"><!--<div class="col-md-11 col-md-offset-1">-->
<p><input type="button" class="btn btn-success" id="subSendResetPassword_btn" value="Reset"></p>
<!--<button type="submit" class="btn btn-success"id="subSendResetPassword_btn">Reset</button>-->
<span id="resetPasswordMsg"></span>
</div>
</div>
<!--</form>-->
</div>
</div>
</div>
<!--reset Password Popup End-->
js - jquery
$(function(){
$("#subSendResetPassword_btn").click(function(){
var email = $("#resetPasswordEmail").val();
var preg = /^\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/; //match Email
if(email=='' || !preg.test(email)){
$("#chkresetPasswordMsg").html("Please fill in the correct email!");
}else{
$("#subSendResetPassword_btn").attr("disabled","disabled").val('Submit......').css("cursor","default");
alert(email);
$.post("sendResetPasswordMail1.php",{mail:email},function(resetPasswordMsg){
if(resetPasswordMsg == ""){
alert("No Msg Return!");
}
if(resetPasswordMsg=="noRegister"){
$("#chkresetPasswordMsg").html("The mailbox is not registered yet!");
//$("#subSendResetPassword_btn").removeAttr("disabled").val('Submit').css("cursor","pointer");
}else{
$(".resetPasswordLayer").html("<h3>"+resetPasswordMsg+"</h3>");
}
});
}
});
})
php - sendResetPasswordMail1.php
$email = stripslashes(trim($_POST['mail']));
$sql = "select * from user where email='$email'";
$query = mysql_query($sql);
$num = mysql_num_rows($query);
if($num==0){//The mailbox is not registered yet! Return 'noRegister'
$resetPasswordMsg = "noRegister";
echo $resetPasswordMsg;
exit;
}
Prevent the default click event
$("#subSendResetPassword_btn").click(function(e){
e.preventDefault()
});

Ajax is not updating data

I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!

How to Upload a file and save to DB using PHP, JavaScript, Bootstrap

everyone..
i've problem using javascript.
i want to make CRUD using Modal(bootstrap), PHP and javascript. but unfortunatelly til now i can't upload a file and save them to database. i have 3 files (index, form, javascript, process) here is my code :
for modal (index) :
<div id="dialog-admin" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"></h3>
</div>
<!-- tempat untuk menampilkan form admin -->
<div class="modal-body"></div>
<div class="modal-footer">
<button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Batal</button>
<button id="simpan-admin" class="btn btn-success">Simpan</button>
</div>
this code for form file :
<form class="form-horizontal" id="form-admin" enctype="multipart/form-data" >
<div> ... bla bla bla.. field.. </div>
<div class="control-group">
<label class="control-label" for="ava">Image</label>
<div class="controls">
<input type="file" id="ava" name="ava" value="<?php echo $ava ?>" required="required" />
</div>
</div>
this code for javascript :
$("#simpan-admin").bind("click", function(event) {
var url = "admin-proses.php";
// mengambil nilai dari inputbox, textbox dan select
var v_username = $('input:text[name=username]').val();
var v_email = $('input:text[name=email]').val();
var v_pass = $('input:text[name=pass]').val();
var v_ava = $('input:file[name=ava]').val();
// mengirimkan data ke berkas transaksi admin-proses.php untuk di proses
$.post(url, {username: v_username, email: v_email, pass: v_pass, ava:v_ava, id: id} ,function() {
// tampilkan data admin yang sudah di perbaharui
// ke dalam <div id="data-admin"></div>
$("#data-admin").load(main);
// sembunyikan modal dialog
$('#dialog-admin').modal('hide');
// kembalikan judul modal dialog
$("#myModalLabel").html("Tambah Data Admin");
});
});
and this code for file process :
require 'dbase.php';
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$imageName = $_FILES['ava']['name'];
$imageSize = $_FILES['ava']['size'];
$imageError = $_FILES['ava']['error'];
if ($imageSize > 0 || $imageError == 0){
$move = move_uploaded_file($_FILES['ava']['tmp_name'], '../uploads/ava/'.$imageName);
if ($move){
echo 'success';
} else {
echo 'failed';
}
} else {
echo 'failed to save file to DB : '.$imageError;
}
mysql_query("INSERT INTO tb_admin VALUES('','$username','$email','$pass','$imageName')") or die (mysql_error());
could you to help me ?
thank
Regard
check whether the post has been done properly in jquery. do step by step debugging.Be sure of getting all input field values.
I would suggest that you should go to this link by W3Schools:
http://www.w3schools.com/php/php_file_upload.asp
It covers all the basics of file uploading.
For Database, go through this:
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

Send data from controller to pop up modal using bootstrap codeigniter

Hello I was going to make a forgot password function using modal bootstrap..
before I have made it without pop up modal.. I do know how to pass the data..
but now I don't know how to send data from controller to pop up modal..
Here is my code:
<div id="forgot-password" class="modal hide fade in" style="display: none; ">
<div class="modal-header" style="background-color:#f39c12; color:#fff;">
<h3 id="helpModalLabel"> Forgot Password</h3>
</div>
<div class="modal-body">
<form class="form-horizontal well" method="post" id="forgot_form" action="<?php echo base_url(); ?>forgotpassword/doforget">
<fieldset>
<legend></legend>
<div class="control-group">
<?php if( isset($info)): ?>
<div class="alert alert-block alert-success fade in" id="alert-message" >
<img src="<?php echo base_url("assets")?>/image/Done.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($info) ?>
</div>
<?php elseif( isset($error)): ?>
<div class="alert alert-block alert-error fade in" id="alert-message">
<img src="<?php echo base_url("assets")?>/img/icon/warning.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($error) ?>
</div>
<?php endif; ?>
<label for="Username" class="control-label span3" >Username</label>
<div class="controls">
<input class="span3" type="text" id="Username" name="Username" placeholder="Input the Registered Username" name="Username"/>
<span id="UsernamehelpText"></span>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Send Password" name="submitbtn"/>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
Close
</div>
</div>
Controller
public function forget()
{
if (isset($_GET['info'])) {
$data['info'] = $_GET['info'];
}
if (isset($_GET['error'])) {
$data['error'] = $_GET['error'];
}
$page_content["page_title"] = "";
$page_content["title"] = "Forgot Password";
$page_content["icon_title"] = "home";
$menu_params["sub_current_navigable"] = "";
$page_content["navmenu"] = $this->load->view("nav_menu", "", true);
$page_content["menu"] = $this->load->view("main_menu_login", $menu_params, true);
if(isset($data)){
$page_content["content"] = $this->load->view("forgotpassword",$data, true);
}else{
$page_content["content"] = $this->load->view("forgotpassword","", true);
}
$this->load->view("template/main_template", $page_content);
}
public function doforget()
{
$this->load->helper('url');
$username= $_POST['Username'];
$checkuser = $this->forgotpassword_model->getusername($username);
print_r($checkuser);
$getemail = $this->forgotpassword_model->getemail($username);
if(!empty($checkuser))
{
$user = $checkuser['0'];
$email = $getemail['0'];
if(!empty($email['email']))
{
$this->sendpassword($user,$email);
$info= "Password has been reset and has been sent to email id: ". $email['email'];
echo $info;
redirect('login/forget?info='.$info, 'refresh');
}else{
$error = "You don't have email, please contact your admin library ";
echo $error;
redirect('login/forget?error=' . $error, 'refresh');
}
}else
{
$error= "You have input wrong username ";
redirect('login/forget?error=' . $error, 'refresh');
echo $error;
}
}
Can someone help me to migrate this to pop up modal? do I need ajax?
I also want to send the error message to pop up modal..
now I'm using 'login/forget?error=' . $error, 'refresh')
Is it possible for me for still using this?
EDIT
to pass your data from Controller to bootstrap modal you need json. to do that try this:
in your controller
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $your_data_array ));
this code change your array data to JSON and then send it to whatever you call this method. with your AJAX call this method and in success get this data parse it with JSON.pars() method and put them to your modal.
In CodeIgniter, before using a model you need to load it. For example you write a model in model folder with name userAuth. Creating a model is as follows:
class UserAuth extends CI_Model{
//your methods
}
In your model you can have some method like forgetPass that will give you an array or data like:
public function forgetPass($dataArray){
//your Code
}
OR
public function forgetPass( $data1, $data2, $data3){
//your code
}
When you want to use your model in a controller method you can load it handily in your controller method or load it in controller constructor like this:
$this->load->model('userAuth');
When you need a method like that, according to the example given you can pass your data to it as:
$this->userAuth->forgetPass($data);
addition:
In CodeIgniter, we have in-built methods to get POST / GET data. They are easy to use and safer. You can use:
$variable = $this->input->post('your_input_name');
OR
$variable = $this->input->get('your_key');
Instead of $_GET['your_key'] or $_POST['your_input_name']

Categories

Resources