I have a problem with a form.
I need to do a login form, but I can't retrieve login data.
This is my view login.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="main">
<div class="container">
<div class="card card-container">
<h1>Control de Asistencia</h1>
<form id="login" class="form-signin" method="post" action="<?php echo
base_url('login/ingresar'); ?>">
<span id="reauth-email" class="reauth-email"></span>
<input type="email" name="email" id="inputEmail" class="form-control"
placeholder="Usuario" required autofocus>
<input type="password" name="password" id="inputPassword" class="form-control"
placeholder="Clave" required>
<br/>
<button class="center btn btn-raised btn-info btn-lg" type="submit">Ingresar</button>
<div class="login__rpta"></div>
</form><!-- /form -->
</div><!-- /card-container -->
</div><!-- /container -->
</div><!--main-->
The controller Login.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('Login_model');
}
function ingresar(){
$email = $this->input->post("email");
$password= md5($this->input->post("password"));
$resp = $this->Login_model->login($email, $password);
if($resp){
$data = [
"id" => $resp->id,
"name" => $resp->nombre,
"nivel" => $resp->nivel,
"login" => TRUE
];
$this->session->set_userdata($data);
}
else{
echo "errorxxx";
}
}
function cerrar(){
$this->session->sess_destroy();
redirect(site_url());
}
}
Javascript custom.js:
$(function () {
$.material.init();
$("#login").submit(function(event){
event.preventDefault();
$.ajax({
url:$(this).attr("action"),
type:$(this).attr("method"),
data:$(this).serialize(),
success:function(resp){
if(resp==="error"){
$('.login__rpta').html("Usuario o clave incorrectos");
console.log(resp);
}
else{
window.location.href = base_url + "welcome/home";
console.log(resp);
}
}
});
});
------ more code ------
});
EDITED: this is the model Login_model.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Login_model extends CI_Model {
function login($email, $password){
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase')) {
echo 'Not connected to a database, or database not exists';
} else {
echo 'Conectado';
}
$this->db->where("email", $email);
$this->db->where("password", $password);
$resultados = $this->db->get("profesores");
if ($resultados->num_rows()>0) {
return $resultados->row();
}
else{
return false;
}
}
}
The console.log from custom.js show me the view (the form) instead of the login parameters, and it redirects me to a 404 error page... What am I doing wrong, please?
This is not my code (I'm just trying to fix it) and I can't see the problem!
Your base_url is defined in codeigniter's config.php, for example like:
$config['base_url'] = 'http://or.org/';
That doesn't mean you can simply use base_url as a variable in javascript hoping to get that value.
But you can echo it out like:
window.location.href = '<?php echo base_url()?>' + 'welcome/home'
or just use the relative path
window.location.href = '/welcome/home'
Related
I am trying to display a form error underneath the input fields but after I click the submit button it will redirect to another page...
Here's my code page controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends CI_Controller{
public function view($page = 'home'){
if(!file_exists(APPPATH.'views/pages/'.$page.'.php')){
show_404();
}
$data['title'] = ucfirst($page);
$this->load->view('template/header');
$this->load->view('pages/'.$page);
$this->load->view('template/footer');
}
public function login(){
echo $this->input->POST('username');
}
public function registercheck(){
echo $this->input->POST('username');
echo $this->input->POST('pwd');
echo $this->input->POST('pwd2');
echo $this->input->POST('fname');
echo $this->input->POST('position');
echo $this->input->POST('contactnumber');
$this->form_validation->set_rules('username', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('pwd2', 'UPPERCASE', 'required|max_lenght[20]');
$this->form_validation->set_rules('fname', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('position', 'USERNAME', 'required|max_lenght[20]');
$this->form_validation->set_rules('contactnumber', 'USERNAME', 'required|max_lenght[20]');
if($this->form_validation->run() == false){
$this->load->view('pages/register');
} else{
echo 'register ok';
}
}
}
?>
And here is my views/pages/register.php
<form action="<?php echo base_url(); ?>pages/registercheck" method="post">
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
<input type="text" class="form-control" id="username" name="username" value="<?php echo set_value('username'); ?>" >
<?php if (form_error('username')) { ?>
<span class="help-block"><?php echo form_error('username'); ?> </span>
<?php } ?>
</form>
Please help me..
What am I doing wrong?
Thank you in advance!
You are in the right direction. But to achieve the desire functionality, you should do as so:
The form and the input validation should be in the same page (controller). In your example, both should be in register.php.
This basic pseudo code should do the trick:
On register page controller:
If method == get:
Display register form.
If method == post:
Check the form data:
If errors exists:
display register page with error.
else:
redirect to ....
Good Luck!
I am having trouble with the browser back button.
When the User press Log out it have to destroy the session and cookies. I wrote the following code:
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<body>
<form name="loginform" method="post" action="<?php echo __PROJECT_LINK__; ?>/php/login_exec.php">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label">
<?php
if( isset($_SESSION['ERRMsg_ARR']) && is_array($_SESSION['ERRMsg_ARR']) && count($_SESSION['ERRMsg_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMsg_ARR'] as $msg) {
echo '<span class="label label-warning" style="margin-left: 5px;">',$msg,'</span>';
}
echo '</ul>';
unset($_SESSION['ERRMsg_ARR']);
}
?>
</label>
</div>
<div class="subnav subnav-fixed nav navbar" style="margin-top: 10px; margin-right: 10px; margin-left: 10px;">
<ul class="nav nav-pills">
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Username</span>
<input type="text" id="inputUserName" name="username" placeholder="Username" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px;">
<span class="label label-default" style="margin-left: 22px;">Password</span>
<input type="password" id="inputPassword" name="password" placeholder="Password" style="margin-left: 5px;">
</li>
<li style="margin-top: 10px; margin-bottom: 10px;">
</li>
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<!--?php $this->btnLogLogin->Render();?-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Sign In</button>
</div>
</form>
</body>
</html>
login_exec.php
<?php
//Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//Include database connection details
require_once('connection.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
if(isset($_POST['username']))
{
//Sanitize the POST values
$username = ($_POST['username']);
$password = ($_POST['password']);
//Input Validations
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
else {
//Login failed
$errmsg_arr[] = 'Username and Password not found';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}else {
die("Query failed");
}
}
?>
welcome.php
<?php include 'qcubed.inc.php'; ?>
<?php
$User_Name = $_SESSION['USER'];
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <?php echo $User_Name; ?></h1>
<h2>Info</h2>
<h2>Sign Out</h2>
</body>
</html>
Info.php
<?php include '../../qcubed.inc.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo __PROJECT_TITLE__; ?> - Full Info</title>
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
</head>
<?php
if(isset($_SESSION['UID']) && $_SESSION['UID'] != "")
{
//Task to do
$User_Name = $_SESSION['USER'];
?>
<body>
<h1>Info about <?php echo $User_Name; ?></h1>
<h2>Sign Out</h2>
</body>
<?php
}
else{
//redirect URL
?>
<script>
alert('You must Login first.');
window.location.href='../../index.php';
</script>";
<?php
exit();
}
?>
</html>
logout.php
<?php
//session_write_close();
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])):
setcookie('User_id', '', $expire, '/');
endif;
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("location: ../index.php");
exit(); # NOTE THE EXIT
?>
After pressing log out from Info.php , when I press the browser back button it is showing my previous Logined user page and session username in Info.php page,
but if I use the following javascript in head section of every page it disable all the browser back button at the time of login also.
<script type="text/javascript">
function disablebackbutton(){
window.history.forward();
}
disablebackbutton();
</script>
I want to disable the browser back button only after the the time of logout.
Please help me.
That became my problem before. On my case i did not disable the back button. what i did is to check the session when the user is logged out. if there has no detected session, redirect the user to log in page or to what page you like the to redirect.. if there is a detected session redirect it to the homepage
rather than disabling the back button, you can add code to every page to see if the user is logged. If they are NOT logged in, redirect to the login page.
You could create a basic class to handle this for you and just create one on every page.
class sessionHandler
{
function __construct($special = NULL)
{
session_set_cookie_params(60 * 60 * 24 * 365); // 1 year
session_start();
// if no user num (empty session) AND this isn't the login page
if (!isset($_SESSION['userID']) && $special != 'LOGIN') {
//send to login page
header("location: login.php");
}
if ($special == 'LOGOUT') {
// This is the logout page, clear the session and
// send the user to the afterLogout page
session_destroy(); // clear session files on server
$_SESSION = Array(); // clear session variable for this session
unset($_SESSION);
// send to login page
header("location: login.php");
}
if ($special == 'LOGIN') {
// This is the login page, see if user is already logged in
// if so, just send them to the afterLogin page
// if not, validate their credentials, and store the USERID
// in the $_SESSION var
if ($this->getUserPermissions($_SESSION['userID'])) {
// send to any page you want
header("location: dashboard.php");
}
}
}
}
Now, on all your pages, put $session = new sessionHandler(); at the top (before anything else is written.
For login and logout pages you'd put:
$session = new sessionHandler('LOGIN');
$session = new sessionHandler('LOGOUT');
Not copy and paste ready, but hopefully that points you in the right direction. :-)
USE THIS CODE in login_exec.php
if($errflag==true) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location:../index.php");
exit();
}
//Create query
$qry="SELECT * FROM admin WHERE user_name='$username' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result)) {
while($row = mysql_fetch_array($result))
{
if($row['User_Status']=="Active"){
$expire=time()+60*60*24*30; //1month
setcookie("User_id", $row['User_id'], $expire);
$name = $row['full_name'];
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$_SESSION['USER'] = $firstname;
$_SESSION['UID'] = $row['User_id'];
$_SESSION['login']=true; //ADD THIS CODE IN login_exec.php
$_SESSION['URights'] = $row['Rights'];
header("location:../welcome.php");
}
else{
$errmsg_arr[] = 'User Status is Block. Please contact your Administrator.';
$errflag = true;
if($errflag) {
$_SESSION['ERRMsg_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../index.php");
exit();
}
}
}
}
now add the code top of the info.php
session_start();
$user=$_SESSION['USER'];
if($_session['login']=true && $_session['user']= $user)
{
code of info.php
}
else
{
header(location:index.php);
}
logout.php
<?php
session_start();
unset($_SESSION['USER']);
session_destroy();
header("Location:index.php");
?>
Just add a condition at all the pages which user can access only if he is login:
if(!isset($_SESSION['UID']) || $_SESSION['UID'] == ''){
// redirect to index or login page
}
At last I solved my problem ..... :-)
I use this following code in
logout.php
<html>
<head>
<script type = "text/javascript" >
window.history.forward();
function preventBack() { window.history.forward(1); }
setTimeout("preventBack()", 0);
window.onunload = function () { null };
</script>
</head>
<body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
Please Wait..
<?php
session_start(); # NOTE THE SESSION START
$expire=time()-60*60*24*30; //1month
if(isset($_COOKIE['User_id'])){
setcookie('User_id', '', $expire);
}
unset($_SESSION['UID']);
unset($_SESSION['USER']);
unset($_SESSION['URights']);
unset($_SESSION['UReg']);
$_SESSION = array();
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
session_unset();
session_destroy();
header("Refresh: 2;url=../index.php");
?>
</body>
</html>
Now it's avoid me to use browser back button after logout and destroy the session.
Thank you all for yours valuable support...
I'm working on login system in codeigniter 3.0 and jquery ajax. I want to post data to controller using ajax and return a value if the data thrown by ajax is match from the mysql database. I also try those suggestion/s from this existing post but i think its not working. I don't want to rely the redirect from codeigniter.
MAIN PROBLEM: i want to check if the username and password data are incorrect, it prompts an error with no page refresh. But i did was throw an boolean value from controller to view for projecting an error-like html tag.
heres the code:
readyLogin.js
var ReadyLogin = function () {
return {
init: function () {
/*
* Jquery Validation, Check out more examples and documentation at https://github.com/jzaefferer/jquery-validation
*/
/* Login form - Initialize Validation */
$('#form-login').validate({
errorClass: 'help-block shake animated', // You can change the animation class for a different entrance animation - check animations page
errorElement: 'div',
errorPlacement: function (error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function (e) {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
},
rules: {
'login-username': {
required: true
},
'login-password': {
required: true,
minlength: 5
}
},
messages: {
'login-username': {
required: "Please enter Administrator's username."
},
'login-password': {
required: "Please provide Administrator's password.",
minlength: 'Your password must be at least 5 characters long.'
}
}
});
$("#form-login").submit(function(){
$.ajax({
type: "POST",
url: $('#form-login').attr('action'),
data: {"login-username": $("#login-username").val(), "login-password": $("#login-password").val()},
dataType: "json",
success: function (returnData) {
alert(data); // to check if there's a thrown data from the view to controller
// below is a "trial" code that checks the status if the controller receives data from ajax
if (returnData.status == true) {
console.log(returnData.status);
} else {
console.log('empty');
}
}
});
});
}
};
}();
controller/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
}
public function index() {
$data['error'] = false;
$result = $data['error'];
if ($_POST) {
$this->load->model('Login_model');
$username = $this->input->post('login-username', true);
$password = $this->input->post('login-password', true);
$user = $this->Login_model->login($username, $password);
if (!$user && $user == null) {
$data['error'] = true; //throwing boolean value to make error html tag
$result = array('status' => true);
json_encode($result);
} else {
$data['error'] = false;
$this->session->set_userdata('username', $user['usename']);
$this->session->set_userdata('password', $user['password']);
redirect(base_url() . 'Maps');
}
}
$this->load->view('Backend/page_ready_login', $data);
}
function logout() {
$this->session->sess_destroy();
redirect(base_url(), 'refresh');
}
}
model/Login.php
<?php
class Login_model extends CI_Model {
function login($username,$password){
$where=array(
'username'=>$username,
'password'=>sha1($password)
);
$this->db->select()->from('admin')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
}
views/Backend/page_ready_login.php
<?php
include 'assets/Backend/inc/config.php';
$template['title'] = 'BCGIS | LOGIN';
$template['page_preloader'] = true;
?>
<?php include 'assets/Backend/inc/template_start.php'; ?>
<!-- Login Container -->
<div id="login-container">
<!-- Login Header -->
<h1 class="h3 text-light text-center push-top-bottom fadeIn animated">
<div class="row">
<div class="col-lg-3 fadeIn animated">
<img src="<?= base_url(); ? >assets/Backend/images/Ph_seal_davao_del_norte_panabo_city.png" style="width: 95px; height: 80px;"/>
</div>
<div class="col-lg-9 fadeIn animated">
<strong>Brgy. Cagangohan Geographical Information System</strong>
</div>
</div>
</h1>
<!-- END Login Header -->
<!-- Login Block -->
<div class="block fadeIn animated">
<!-- Login Title -->
<div class="block-title">
<h2>Administration Login</h2>
</div>
<!-- END Login Title -->
<!-- Login Form -->
<form id="form-login" action="<?= base_url(); ?>" method="post" class="form-horizontal">
<?php if ($error == true) { ?>
<h5 class="alert alert-danger shake animated" id="login-error">Your Username/Password is incorrect!</h5>
<?php } ?>
<div class="form-group">
<div class="col-xs-12">
<input type="text" id="login-username" name="login-username" class="form-control" placeholder="Username..">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="password" id="login-password" name="login-password" class="form-control" placeholder="Password..">
</div>
</div>
<div class="form-group form-actions">
<div class="col-sm-offset-2 col-sm-8 text-center">
<center>
<button type="submit" id="login-button" name="login-button" class="btn btn-effect-ripple btn-block btn-primary"><i class="fa fa-check"></i> Sign In</button>
</center>
</div>
</div>
</form>
<!-- END Login Form -->
</div>
<!-- END Login Block -->
<!-- Footer -->
<footer class="text-muted text-center fadeIn animated">
<small><span id="year-copy"></span> © <?php echo $template['name'] . ' ' . $template['version']; ?></small>
</footer>
<!-- END Footer -->
</div>
<!-- END Login Container -->
<?php include 'assets/Backend/inc/template_scripts.php'; ?>
<!-- Load and execute javascript code used only in this page -->
<script src="<?= base_url(); ?>assets/Backend/js/pages/readyLogin.js"> </script>
<script>
$(function () {
ReadyLogin.init();
});
</script>
<?php include 'assets/Backend/inc/template_end.php'; ?>
Any suggestion/s and help fixing this is much appreciated. Thanks.
In your controller method, change this:
if (!$user && $user == null) {
To this:
if (!$user || $user == null) {
I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.
Hello I am wondering if this is possible? Having two different forms on the same page using the jquery post to send it php to do some checking. The first from works flawlessly, however when I go to the second form I get an error saying it is an undefined variable but I am using the exact same method I used for the first form. It will load anything echoed in the php page for the feed form but will not echo back what I am typing in. Is there a better, more correct way to do it?
This is not for a real site, just testing for a project I am working on.
HTML:
<form action="php/signup.php" method="post" class="form-inline" name="signupForm">
<input type="text" maxlength="20" name="username" id="user_in">
<input type="password" maxtlength="20" name="password" id="pass_in">
<input type="submit" name="submit" Value="Sign Up">
</form>
<div id="feedback"></div> <!-- Feedback for Sign Up Form -->
<br /><br />
<form name="feedForm">
<input type="text" id="feed_in" name="feed_me_in" placeholder="feed">
<div id="feedme"></div> <!-- FEEDback for feed form -->
</form>
<script src="js/jquery-1.9.1.js"></script>
JavaScript:
<script>
$(document).ready(function() {
$('#feedback').load('php/signup.php').show();
//SIGN IN FORM
$('#user_in, #pass_in').keyup(function() {
$.post('php/signup.php', { username: document.signupForm.username.value,
password: document.signupForm.password.value },
function(result) {
$('#feedback').html(result).show
});
});
$('#feedme').load('php/feed.php').show();
//FEED FORM
$('#feed_in').keyup(function() {
$.post('php/feed.php', { feed: document.feedForm.feed_me_in.value },
function(result) {
$('$feedme').html(result).show
});
});
});
</script>
PHP for Feed Form:
<?php
$feed = mysql_real_escape_string($_POST['feed']);
if(isset($feed)) {
echo $feed;
} else {}
?>
PHP for the Sign Up Form:
<?php
if(isset($_POST['username'])) {
include_once('connect.php'); //Connect
$username = mysql_real_escape_string($_POST['username']);
$sql1 = "SELECT username FROM users WHERE username='$username'";
$check = mysql_query($sql1);
$numrows = mysql_num_rows($check);
if(strlen($username)<=4) {
echo "Username is too short";
} elseif($numrows == 0) {
echo "Username is available";
} elseif($numrows > 0) {
echo "Username is already taken";
}
} else {
echo "Please type a username";
}
?>
$('$feedme').html(result).show
should be
$('#feedme').html(result).show();