I am using codeigniter HMVC. I'm trying to create a sign up form that opens when sign up button is clicked. However, validation errors for the sign-up form appears on the parent page where the login form is located the dialog also closes after submitting data. What I want to do is to display the errors on the sign-up form dialog.
vw_login.php
<button id="show-sign-up-dialog">Sign Up</button>
<dialog id="sign-up-dialog" >
<button id="close"><i class="fa fa-times"></i></button>
<?php echo form_open('user/sign_up', 'id = "reg_form" class="form-horizontal" role="form"'); ?>
<!-- REGISTER USERNAME -->
<div class="form-group">
<div class="col-12">
<label for="name"></label>
<?php
$regi_username_attrib = array(
'name' =>'register_username',
'class'=>'form-control mdl-input-login',
'rows' =>'4',
'placeholder'=>'Username'
);
echo form_error('register_username');
echo form_input($regi_username_attrib, set_value('register_username', ''));
?>
</div>
</div>
//Script to submit sign up form
<script>
$(document).on("click", "#btn_sign_up", function ()
{
$.ajax({
type: "POST",
url: "<?php echo base_url('user/sign_up');?>",
data: $(this).serialize(),
success: function(data) {
var obj = $.parseJSON(data);
if(obj!==null)
{
$('#error_msg').html(obj['error_message']);
}
}});
});
</script>
//Script to open sign up form
<script>
var dialog_AddEntry = document.querySelector('#sign-up-dialog');
var showDialogButton_AddEntry = document.querySelector('#show-sign-up-dialog');
if (! dialog_AddEntry.showModal) {
dialogPolyfill.registerDialog(dialog_AddEntry);
}
showDialogButton_AddEntry.addEventListener('click', function() {
dialog_AddEntry.showModal();
});
dialog_AddEntry.querySelector('#close').addEventListener('click', function() {
dialog_AddEntry.close();
});
</script>
Controller
class User extends My_Controller {
public function index()
{
$this->load->view('vw_login');
}
public function login()
{
//|is_unique[tbl_user.user_username]
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE) // If username and password is invalid
{
$this->load->view('vw_login');
}
else
{
}
}
public function sign_up()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('register_username', 'Username', 'trim|required');
if ($this->form_validation->run() == FALSE) // If username and password is invalid
{
$this->load->view('vw_login');
$data = array('error_message' => form_error('register_username'));
echo json_encode($data);
}
else
{
}
}
}
Add the following
<span id="error_msg"></span>
after
<label for="name"></label>
Related
I'm trying to submit form data from view to controller using Ajax post and return success message.And ajax in my view send data to function in controller successfully but controller function does not return response back to ajax success function.
my Controller - profile.php
function save()
{
$response = array();
$this->form_validation->set_rules('fname', 'Title cant be empty ', 'required');
if ($this->form_validation->run() == TRUE)
{
$param = $this->input->post();
unset($param['submit']);
$param['rid']=$this->session->userdata('id');
$profile_id = $param['profile_id'];
unset($param['profile_id']);
if($profile_id == 0)
{
$inserts = $this->profile_model->insert($param);
if( $inserts>0){
$response['status'] = TRUE;
$response['notif'] ="success add profile details";
}else{
$response['status'] = FALSE;
$response['notif'] = 'Server wrong, please save again';
}
}else{
}
}else{
$response['status'] = FALSE;
$response['notif'] = validation_errors();
}
echo json_encode($response);
}
view - profile_new_user.php
?>
<form method="POST" id="form_profile" action="<?php echo base_url().'profile/save'; ?>">
<input type="hidden" name="profile_id" value="0"><!-------event id---------->
<div class="form-group">
<label>Prefix</label>
<select name="prefix" class="form-control">
.
.
.
</div>
<div class="form-group">
<input type="submit" name="submit" value="Save" class="btn btn-info" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form_profile").submit(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
dataType :'JSON',
data: $(this).serialize(),
success: function(data)
{
if(data.status){
alert('ok');
}else{
alert('not ok');
}
}
})
});
});
model - profile_model.php
function insert($data)
{
$this->db->insert('user_profile', $data);
return $this->db->insert_id();
}
after I click submit button page redirect to url - http://localhost/ptm6/profile/save and page shows
{"status":true,"notif":"success add profile details"}
in plain text.
I expect to show alert message without any redirection.
Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.
Hi I am creating a login form with CodeIgniter using ajax but it is not function properly as i want. it is getting redirected to the page which I am doing through ajax but doesnot perform the do_login function. if i click login without entering any fields it does not shows fields required whereas i have given the validation code in do_login function. Please suggest me the appropriate solution for the problem how to redirect through ajax using those functions.
This is my controller user.php
class User extends CI_Controller {
public function index()
{
$this->load->view('login');
}
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
else{
echo "loggedIn"; // where to put this echo to make it work through ajax
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
redirect('user/members');
}
}
public function members()
{
if($this->session->userdata('is_logged_in')){
$this->load->view('home');
}
else{
redirect('user/restricted');
}
}
public function restricted()
{
$this->load->view('restricted');
}
public function verifyUser(){
$username=$this->input->post('username');
$password= $this->input->post('password');
$this->load->model('LoginModel');
if($this->LoginModel->login($username, $password)){
return true;
}
else{
$this->form_validation->set_message('verifyUser','Invalid Email or Password: Please enter it correctly');
return false;
}
}
public function logout(){
$this->session->sess_destroy();
redirect('user/index');
}
}
?>
This is my view file login.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://127.0.0.1/simple_login_comp/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
//window.location.replace("http://127.0.0.1/simple_login_redirect/index.php/user/home");
//window.location.href="http://127.0.0.1/simple_login_comp/index.php/user/members";
}
else if(data== 'sorry'){
alert("sorry");
}
//else{
// alert(data);
//}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="span12">
<div class="well">
<center><h1>Be a member of Mrwebsiter</h1></center>
</div>
</div>
</div>
<h1>Login</h1>
<p>Please fill your details to login</p>
<form action="" id="frm_login" method="post">
Username :</br>
<input type="text" name="username" id="username"/></br>
Password :</br>
<input type="password" name="password" id="password"/></br>
<input type="submit" value="Login" name ="submit"/>
</form>
<div class="row">
<div class="span12">
<div class="well">
<center><h3>copyright</h3></center>
</div>
</div>
</div>
</div>
</body>
</html>
And this is my model LoginModel.php
<?php
class LoginModel extends CI_Model {
public function login($username, $password)
{
$this->db->select('username', 'password');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query= $this->db->get();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
}
?>
My login form is not working, can anyone suggest me how to make it run and where have i done mistake. when i redirect it through ajax it does not validate the input through do_login function it directly redirects to the page.
here is your problem
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
change this to
if($this->form_validation->run()== false){
echo "sorry";exit
}
I suggest that you use echo json_encode($data); on you controller where $data is an associative array containing your require fields or any prompt.
On your ajax handle the callback with -
success: function(data) {
var response = eval('(' + data + ')');
// DOM codes here
} // rest of the codes here
If you're not familiar with this and you want to push this ajax thing on you login system, I suggest you check out javascript dom, callbacks and other related stuff.
On your Controller
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
}
else{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
echo "loggedIn"; // where to put this echo to make it work through ajax
}
}
On your view
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
window.location ="http://127.0.0.1/simple_login_redirect/index.php/user/members");
}
else if(data== 'sorry'){
alert("sorry");
}
}
});
});
});
</script>
CodeIgniter Ajax is not working for me.
This is what I have tried so far.
v_login.php
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('#username').val(),
password : $('#password').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('c_login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<div class="container">
<div class="jumbotron">
<?php
$attributes = array('class' => 'form-signin');
echo form_open('c_login', $attributes); ?>
<h2 class="form-signin-heading">VMS Login System</h2>
<input type="username" name="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<input class="btn btn-primary" type="submit" id="submit" value="Login">
<input class="btn btn-primary" type="reset" value="Cancel">
<?php echo form_close(); ?>
<div id="message">
</div>
</div>
</div>
C_login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
}
function index() {
$this->load->view('include/header');
$this->load->view('v_login');
$this->load->view('include/footer');
}
function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user == '1') {
echo 'login successful';
} else {
echo 'unknown user';
}
}
}
}
}
/* End of file c_login.php */
/* Location: ./application/controllers/c_login.php */
m_access.php
<?
class M_access extends CI_Model {
public function check_user($username,$password) {
$this->query = $this->db->select('COUNT(*)')->from('users')->where(array('username'=>$username,'password'=>$password))->limit(1)->get();
return $this->query->row_array();
}
}
I don't know what's wrong, I have already set up config.php and routes. But it's not working at all. Any ideas? Help is much appreciated. Thanks.
After a long chat with OP the solution is this
Your model
class M_access extends CI_Model {
public function check_user($username,$password) {
$args = array(
'username' => $username,
'password' => $password
);
$query = $this->db->select('*')->from('users')->where($args)->get();
if($query->num_rows()) {
return $query->row_array();
}
return false;
}
}
In your controller, use
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'), $this->input->post('password'));
if($user) {
// right user
}
else {
// wrong user
}
Don't need to send ajax:1 because jQuery sends a request header to server, like this
X-Requested-With': 'XMLHttpRequest'
and in CodeIgniter you may check for ajax request using
if($this->input->is_ajax_request()){
// it's an ajax request
}
Also, you asked for a gif loader to shw, so this could be used as
$('#submit').click(function() {
var form_data = { ...};
// show the gif loader
$.ajax({
...
data: form_data,
success: function(msg) {
// hide the gif loeader
$('#message').html(msg);
}
});
});
Update : For inserting an image you may check this fiddle example, like
$('#submit').click(function(e){
e.preventDefault();
var loader = $('<img/>', {
'src':'url_of_the_image',
'id':'ajax_loader'
});
loader.insertAfter($(this));
});
and to remove the image in your success callback, you may use
$('#ajax_loader').remove();
error 404 due to the calling path because file name with "C" and you calling it with "c", rather than that
in my opinion you need to have a deeper look at codeigniter form validation helper
before you try the ajax call
once you did it server side perfectly & if you still want to validate using ajax , make another function as a webservice only for this purpose along the orignal server side validation function , it'd be something like that
function ajax_check(){
$username_check=true;
//your code goes here to check if username unique or not and result assigned to $username_check
if(!$username_check){
echo json_encode('fail');
return;
}
echo json_encode('success');
}
I am having trouble in combining CodeIgniter and AJAX. I have a sign up form. What I want is that when user clicks on sign up button on my home page, he gets a sign up form in pop up. If he enter wrong details in the form , he is prompted on the pop up itself that your details are invalid, He must not be redirected to new page to show errors. So I am using bpopup to make my form pop up and ajax request, but I am not able to perform form_validation, I am little confused. If user does not pass form validation a HTML document is alerted to the user because of view being loaded. If I will not load the view , it will not show login page. If I will directly load view , how will I show user individual errors , like password must be 6 characters long. Here is my code :
My login view :
<html>
<head>
<title>Sign In</title>
<script type="text/javascript">
var frm = $('form');
frm.submit(function () {
$("#status").empty();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if (data == "invalid") {
$('#status').html("Invalid Login Details");
}
else if(data == "valid")
{
$('#status').html("Login successful");
setTimeout(function(){
location.reload();
},600);
}
else
{
$('#status').html("Your Account is not Activated");
}
}
});
return false;
});
</script>
</head>
<body>
<div class="Header">
<h3>Sign In </h3>
</div>
<div id="status"></div>
<div class="main">
<?php echo form_open('xyz/signin'); //Renders the form element and adds extra functionality like Adds a hidden CSFR prevention field.?>
<h5>Email</h5> // For the time being I have remove echo form_error.
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="25"/>
<h5>Password *</h5> // For the time being I have remove echo form_error.
<input type="password" name="password" size="25"/>
<div><input type="submit" value="Submit" "/></div>
</form>
</div>
</body>
</html>
and here is my sign in function of xyz controller :
public function signin()
{
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'email',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|xss_clean'
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run() == FALSE) /
{
$this->load->view('pinflag/login.php');
}
else //format of form is correct
{
$email = $this->input->post('email');
$password = md5($this->input->post('password'));
$data = array(
'email' => $email,
'password' => $password
);
$result = $this->user_model->get_users($data);
if($result->num_rows == 1) //login details are correct
{
$result = $result->result_array();
if($result[0]['status'] == 0)
{
echo "notActivated";
}
else
{
$this->session->set_userdata('id',$result[0]['id']);
$this->session->set_userdata('name',$result[0]['fname']);
echo "valid";
}
}
else //when user enter invalid login details
{
echo "invalid";
}
}
}
Sorry, indentation got all messed up when I pasted the code here.
i didn't get how your pop is coming but for error and success messages try
$this->session->set_flashdata("msg","<span class='m_error'>".$this->lang->line('global_insert_error')."</span>");
before your page to be loaded.
and inside your login view any part
if($this->session->flashdata('msg'))
{
echo $this->session->flashdata('msg');
}