In my app I want to make a login page. I want do do this login using ajax jquery. If login success it navigate to next page or show a error message in a div.
this is my code
<form role="form">
<div class="form-group radio-inline">
<label><b>I Am</b></label>
<input type="radio" name="category" value="s"> Student
<input type="radio" name="category" value="t"> Teacher
<input type="radio" name="category" value="p"> Parent
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email address">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</form>
<div id="error">
</div>
jquery
$(document).on('click','.btn',function() {
var email = $("#email").val();
var password = $("#password").val();
var category = $("input[name=category]:checked").val();
$.ajax({
url: "../logincheck.php",
type: "POST",
data: {category:category,email:email,password:password},
success:function(data) {
if (data==='studentlogin') {
window.location.href = '../student/index.php';
}
if(data==='teacherlogin'){
window.location.href = '../teacher/index.php';
}
if(data==='teachersubject') {
window.location.href = '../teacher/subjectadd.php';
}
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
}
});
});
logincheck.php
$category=$_POST['category'];
$email=$_POST['email'];
$pwd=$_POST['password'];
if ($category == 's') {
$result=mysqli_query($conn,"SELECT studentid,studentfname FROM studentinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$_SESSION['snstudentid']=$res[0] ;
$_SESSION['snstudentfname']=$res[1] ;
echo "studentlogin";
//header("location:student/index.php");
exit();
}
else{
echo "error";
//header("location:pages/login.html");
}
} elseif ($category == 't') {
$result=mysqli_query($conn,"SELECT teacherid,teacherfname FROM teacherinfo WHERE emailid='$email' and pwd='$pwd'");
$res=mysqli_fetch_array($result);
if($res[0]>0){
$check_subject = mysqli_query($conn, "SELECT count(teachersubjectid) FROM teachersubject WHERE teacherid='$res[0]'");
$subject_result = mysqli_fetch_array($check_subject);
if ($subject_result[0]>0) {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teacherlogin";
//header("location:teacher/index.php");
exit();
} else {
$_SESSION['snteacherid']=$res[0];
$_SESSION['snteacherfname']=$res[1];
echo "teachersubject";
//header("location:teacher/subjectadd.php");
exit();
}
} else{
echo "error";
//header("location:pages/login.html");
}
}
that error message show for few second and then it goes.I do that error class style display:none;
How I do that?Please help me.
Have a look at what this code does:
else {
window.location.href = 'login.html';
$("#error").html("Invalis Email/Password");
}
yes, it redirects the page to login.html, then, while the page is loading it puts up the error message, then the page load completes and, in your initial login page, the error message is empty.
Remove the line:
window.location.href = 'login.html';
assuming you are already on login.html.
If <div id="error"> has a style of display:none;, then its contents will not be displayed. Inside of the ajax success callback, $("#error").html("Invalis Email/Password"); needs to be $("#error").html("Invalis Email/Password").show(); to set display:block;. See .show().
Related
view: login.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="tab-pane" id="profile" role="tabpanel" data-mh="log-tab">
<div class="title h6">Login to your Account</div>
<form class="content">
<div class="login_success"></div>
<div class="row">
<input class="form-control" placeholder="" type="email" id="elogin">
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox">Remember Me
</div>
Login
</div>
</div>
</form>
</div>
controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
if($email=='' || $password=='')
{
echo json_encode(array('error' => 'All fields are mandatory. Please fill all details.'));
}
else
{
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
}
In this code, I am creating a login module which works fine. Now, I also want to integrate the remember me option when user check remember me checkbox server ask to want to save detail or not. When user logout it doesn't require to fill it's detailed again inside the login form. Once the user checks on remember me checkbox. So, How can I do this? Please help me.
Thank You
You can make this by using cookie.
try following code:
//php (controller):
//after success login
if($remember){
//set cookie
$this->input->set_cookie('email', $email, 86500);
$this->input->set_cookie('password', $password, 86500);
}else
{
//delete cookie
delete_cookie('email');
delete_cookie('password');
}
view: login.php
//set cookie value if checked remember me.
<div class="row">
<input class="form-control" value="<?php if (get_cookie('email')) { echo get_cookie('email'); } ?>" placeholder="" type="email" id="elogin">
<input class="form-control" value="<?php if (get_cookie('password')) { echo get_cookie('password'); } ?>" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox" <?php if (get_cookie('email')) { ?> checked="checked" <?php } ?>>Remember Me
</div>
You can create the cookie with your javascript when you get the response of your ajax call. You should use document.cookie() if you choose this way to do.
If you choose the server side, CodeIgniter have a Cookie Helper. For use it, you have to add it 'cookie' on your autoload. You can load it with this line too :
$this->load->helper('cookie');
when the helper is loaded, you have to create the cookie in your controller like this :
$this->input->set_cookie('cookie_name', $value, time_in_seconds);
I am working with ajax and php. I want to display message on another page after user successfully added using Ajax. I have tried so much. It's working when first display "Success" message on popup and afrer redirect on another page. But i want to first redirect on another page and after display message.
User Add Page:
<form action="<?php echo $action_link; ?>" method="post" id="form_user_profile" class="form-horizontal" novalidate="novalidate">
<input type="hidden" id="id" name="id" value="<?php echo $id; ?>">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control" name="fname" value="<?php echo $user_db[0]['fname']; ?>">
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<input type="submit" class="btn green" name="submit" value="<?php echo $addupdate_msg; ?>">
</div>
</div>
</div>
</form>
Ajax in Validate
$("#form_user_profile").validate({
rules: {
fname: {
required: true
}
},
messages: {
fname: "Please enter first name"
},
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
if(response == 1){
bootbox.alert("User has been added successfully.", function() {
window.location.href= "<?php echo $user_list; ?>";
});
}
}
});
}
});
Action
if (isset($_REQUEST['submit']) && $_REQUEST['submit'] == "Add") {
$fname = mysqli_real_escape_string($obj->CONN, $_REQUEST['fname']);
$user->setfname($fname);
$insert = $user->insert();
ob_get_clean();
if($insert){
echo '1';
$_SESSION['msg'] = "New user has been added successfully.";
}else{
echo '0';
}
exit;
}
The success popup appears before the user is redirected because of the following code:
if(response == 1){
bootbox.alert("User has been added successfully.", function() {
window.location.href= "<?php echo $user_list; ?>";
});
}
If you wish to show a message on the new page instead, just redirect the user
if(response == 1)window.location.href= "<?php echo $user_list; ?>";
On the new page where you send the customer after success, show the message with something like
$(function() {
bootbox.alert(<?= $_SESSION['msg'] ?>);
});
You can check if there is a $_SESSION['msg'] set on the page you are directing it to, if set then alert.
Jquery:
if(response == 1){window.location.href= "<?php echo $user_list ?>";}
Then, $user_list page:
if(isset($_SESSION['msg'])){
echo '$(document).ready(function(){
bootbox.alert('.$_SESSION['msg'].');
})';
}
Note, I'm using the single quotes so that PHP doesn't think $ is a variable.
I am making a simple registration system in Ionic Cordova. I am sending the data from the form to server through an AJAX call but I am not getting anything in response form the sever. When I made a different conventional form and dent the data to the same script I got the proper response. I am able to figure out the issue.
form:-
<div class="list" id="register">
<label class="item item-input item-floating-label">
<span class="input-label">Name</span>
<input type="text" placeholder="Name" id="name">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label">Email</span>
<input type="email" placeholder="Email" id="email">
</label>
<br>
<label class="item item-input item-floating-label">
<span class="input-label">Password</span>
<input type="password" placeholder="Password" id="pass">
</label><br>
<button class="button button-full button-assertive" id="signup">
Submit
</button>
AJAX call:-
$(document).ready(function(){
$("#signup").click(function(){
console.log("Button clicked");
var name=$("#name").val();
var email=$("#email").val();
var pass=$("#pass").val();
var dataString="name="+name+"&email="+email+"&pass="+pass+"&signup=";
if($.trim(name).length>0 && $.trim(email).length>0 && $.trim(pass).length>0)
{
$.ajax({
type: "POST",
url: "http://127.0.0.1/ionic/reg.php",
data: {dataString: dataString,signup:true},
success: function(data){
if(data =="success")
{
alert("Thank you for Registering with us! you can login now");
}
else if(data =="exist")
{
alert("Hey! You alreay has account! you can login with us");
}
else if(data =="failed")
{
alert("Something Went wrong");
}
}
});
}
return false;
});
});
PHP script:-
<?php
header('Access-Control-Allow-Origin: *');
include 'db_connect.php';
if(isset($_POST['signup']))
{
$name=trim($_POST['name']);
$email=trim($_POST['email']);
$password=trim($_POST['pass']);
$login=mysqli_num_rows(mysqli_query($con,"select * from `phonegap_login` where `email`='$email'"));
if($login!=0)
{
echo "exist";
}
else
{
$q=mysqli_query($con,"insert into `phonegap_login` (`name`,`email`,`password`) values ('$name','$email','$password')");
if($q)
{
echo "success";
}
else
{
echo "failed";
}
}
echo mysql_error();
}
?>
I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">
I have a form for user to update their info using jquery + Ajax. Everything is working great so far, but WHen i change input type="email" to input type="text" in the fullname section of the form and click update. It got error??? It won't run the php file in ajax. I don't see any connection which causes this error? Anyone please sugguest why? But if I change input type in the fullname section back to "email". It works! This is so weird!
Here is my form:
<div id="changeuserinfo_result"></div>
<form role="form" method="post">
<div class="form-group">
<label>Fullname</label>
<input type="text" class="form-control" id="changename" name="changename" value="<?php echo $_SESSION['name'] ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="changepass" name="changepass" value="<?php echo $_SESSION['pass'] ?>">
</div>
<button class="btn btn-default" id="changeuserinfo">Update</button>
</form>
Here is my jquery code:
$(document).ready(function(){
$('#changename').focus();
$('#changeuserinfo').click(function(){
var changename = $('#changename');
var changepass = $('#changepass');
var changeuserinfo_result = $('#changeuserinfo_result');
changeuserinfo_result.html('loading...');
if(changename.val() == ''){
changename.focus();
changeuserinfo_result.html('<span class="errorss"> * Empty fullname</span>');
return false;
}
else if(changepass.val() == ''){
changepass.focus();
changeuserinfo_result.html('<span class="errorss">* Empty password</span>');
return false;
}
else {
var UrlToPass = {changename:changename.val(),changepass:changepass.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'changeuserinfo.php',
success: function(responseText){
if(responseText == 1){
$('#changeuserinfo_result').html('<span style="color:green"> Update OK</span>');
}
else{
$('#changeuserinfo_result').html('<span class="errorss"> Update fail. Try again</span>');
}
}
});
}
});
});
You have no closing tags on your inputs.
It should be <input type="text"... />
Also set the doctype of the page to HTML5.
<!DOCTYPE HTML>
....
</html>