Show error message after a page refresh - codeigniter

I have a login form that I'm doing 2 part validations: The client-side and the server side.
Client-side: check if valid email, check if password is minimal 6 characters, etc. If something goes wrong on the client-side I can show the user the error messages on the same page with the login form, because it page never got reloaded because it will not send a post to the server if the client-side validation isn't true.
But when it is true, then I'm doing a server side validation -> check if email and password matches to effectively log in into the website. But if the login credentials aren't matching, I need to show a error message. This is the part where I'm stuck. Where and how do I get a message on the same page (login form) because page gets posted and refreshed so I'm losing data. Now when credentials aren't correct I'm redirecting the user back to the login page, but without any messages. But I'm trying to achieve that he'll see the message 'credentials aren't correct'. Can someone help me with this?
Login View
<?php
$loginEmail = array('placeholder' => "Email", 'name' => "loginEmail");
$loginPassword = array('placeholder' => "Wachtwoord", 'name' => "loginPassword");
$loginSubmit = array('name' => "loginSubmit", 'class' => "btn", 'value' => "Inloggen");
echo form_open('login/inloggen', array('class' => 'grid-100 formc'));
echo form_input($loginEmail, set_value('loginEmail'));
echo form_password($loginPassword);
echo form_submit($loginSubmit);
echo form_close();
?>
Login Controller
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->view('profile_view');
}
else{
$data['content'] = 'login_view';
$this->load->view('templates/template', $data);
}
}
function inloggen(){
if($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules') == FALSE){
$this->index();
}
else{
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
}
else{
$this->index();// If credentials aren't correct, redirect them to login page. But how I set a message here?
}
}
}
}
Login Model
function validate(){
$this->db->where('email', $this->input->post('loginEmail'));
$this->db->where('password', md5($this->input->post('loginPassword')));
$query = $this->db->get('tbl_users');
if($query->num_rows == 1){
return true;
}
else{
return false;
}
}

I will prefer do to in one controller, and it will be more clear. I make one simple example, just to tell you the way how I think is good.
function login(){
$data['error_message'] = "";
$data['username'] = $this->input->post('username');
$data['password'] = $this->input->post('password');
if($this->input->post('loginSubmit')){
// Make rules of validation that need to be required
if($this->form_validation->run('login_validation_rules')){ // If true it goes IN
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile'); // Go IN profile
} else {
$data['error_message'] = "Something went wrong"; // This error you write on View
}
}
}
$this->load->view('login_view', $data) //Load view of login
}
I didn't test, and it will need to adapt in your data, but I just want to explain the way. It you have any problem, write an comment, and we will find the solution together.

I have solved this problem like so: Basically when the model sends a false. I make var with a message in it and then in my index I check if that var is there or not.
The only thing I want to know is, is it okay to set a message in my controller or should I have done that somewhere elsewhere??
function index(){
$logged_in = $this->logged_in->is_logged_in();
if($logged_in){
$this->load->view('profile_view');
}
else{
//Check here if my redirection submitted also a message
if(isset($this->ongeldig)){
$data['ongeldig'] = $this->ongeldig;
}
else{
$data['ongeldig'] = '';
}
$data['content'] = 'login_view';
$this->load->view('templates/template', $data);
}
}
function inloggen(){
if($this->input->post('loginSubmit')){
if($this->form_validation->run('login_validation_rules')){
$this->load->model('login_model');
$query = $this->login_model->validate();
if($query){
$data = array(
'username' => $this->input->post('loginEmail'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('profile');
}
else{// set a error message, when the models function returns false.
$this->ongeldig = "Ongeldig wachtwoord/gebruikersnaam";
$this->index();
}
}
else{
$this->index();
}
}
}

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Post method in REST API using codeigniter

when i use following method and pass body key as fail (non defined key) and some value getting pass message in return and empty row gets inserted in table, How do I validate?
Function that I use in REST API,
function categories_POST() {
$title = $this->post('title');
$no = $this->post('no');
$id= $this->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
}
My model,
function addDetails($x, $y, $z) {
$check = "INSERT INTO categories (title,no,id) VALUES ('$x','$y','$z')";
$query = $this->db->query($check);
if($this->db->affected_rows() > 0) {
return "pass";
} else {
return "fail";
}
}
quite honestly, you'd be better off using the query builder and (depending on what style you follow(fat/skinny controllers/models)) letting the model deal with $this->post() for processing.
Is this Phil Sturgeons/Chris A's rest server?
Something like:
function categories_post() { // doesn't need to be POST()
$this->load->model('model_check');
$msg = $this->model_check->addDetails()
if ($msg)
{
$this->response([
'status' => TRUE,
'message' => 'pass'
], REST_Controller::OK);
}
// default to fail
$this->response([
'status' => FALSE,
'message' => 'fail'
], REST_Controller::HTTP_BAD_REQUEST);
}
Your model,
function addDetails() {
// this only checks to see if they exist
if (!$this->post() || !$this->post('x') || !$this->post('y') || !$this->post('z')) {
return false;
};
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
return false; // defaults to false should the db be down
}
IF you mean form_validation you can use this instead of the above.
function addDetails() {
$this->load->library('form_validation');
$this->form_validation->set_rules('x', 'X', 'required');
$this->form_validation->set_rules('y', 'Y', 'required');
$this->form_validation->set_rules('z', 'Z', 'required');
if ($this->form_validation->run() == true)
{
$insert = array(
'x' => $this->post('x'),
'y' => $this->post('y'),
'z' => $this->post('z'),
);
if($this->db->insert('categories', $insert))
{
return true;
}
}
return false; // defaults to false should the db be down
}
This is quite verbose, there's shorter ways to do it, but I'd rather make it easy to figure out.
Two ways of get post values in CodeIgniter
$title = $this->input->post('title');
$no = $this->input->post('no');
$id= $this->input->post('id');
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
or
extract($_POST);
Then direct access post name
$this->load->model('model_check');
$msg = $this->model_check->addDetails($title , $no , $id);
$this->response($msg);
Best way is directly access post values in model files (not in controller)
Don't need the pass the POST values in model function.
If you have more queries, then ask to me

Restriction for not allowing same email and password in the database for my signup form

i want to make a restriction in my signup form which the user cant signup with the already exists email and password..
in my controller:
i already make a rules or callback
array(
'field' => 'txt_email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_check_if_valid_email|trim',
),
check_if_valid:
public function check_if_valid_email()
{
$where = array('email' =>$this->input->post('txt_email'),'password' =>$this->input->post('txt_password'));
$this->load->model('database_model');
if ($user = $this->database_model->validate_user('user', $where))
{
foreach ($user as $row) {
$checkemail = $row->email;
$checkpassword = $row->password;
}
if ($checkemail == $this->input->post('txt_email')){
$this->form_validation->set_message('check_if_valid_email', 'Email already existed!');
return false;
}
else
{
if ($checkpassword = $this->input->post('txt_password'))
{
$this->form_validation->set_message('check_if_valid_email', 'Email already exists!');
return false;
}
else
{
return true;
}
}
}
}
in my model:
public function validate_user($table, $where)
{
$this->db->where($where);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
CodeIgniter's Form Validation library comes with the rule you're looking for, called: is_unique
http://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
Your validation rules will look like this;
required|valid_email|is_unique[users.email]|trim
All you have to set it the table and column you want to be unique (users.email).
Hope this helps.

How can I process a Response directly in Laravel?

I'm writing code in my Laravel Controller and I want to trap some exceptions firing a response directly without returning something to the routes.
For example, I wrote a method for returning a 404 response:
public static function respondNotFound( $message = null, $instantResponse = false )
{
$message = $message ? $message : "Not Found";
$statusCode = self::STATUS_NOTFOUND;
return self::makeResponse( array( 'status' => $statusCode, 'message' => $message ), $statusCode );
}
This method calls another one for building an Illuminate Response
protected static function makeResponse( $data, $statusCode = self::STATUS_OK, $instantResponse = false )
{
$response = Illuminate\Support\Facades\Response::json( $data, $statusCode );
$response->setCallback( Input::get( 'callback' ) );
if( $instantResponse ) {
//..... I want to fire my Response here!
}
else {
return $response;
}
}
Referring to the method above, I want to specify that my response must be fired directly rather than being returned outside, avoiding a "waterfall of return".
My solution is to set up some php headers and then kill the script, but I think that it's a bit rough.
Can someone help me?
Thanks in advance.
I'm confused - why dont you just use the App::missing() filter and handle your 404 in there?
In 'app/start/global.php' add:
App::missing(function($exception)
{
if (Request::ajax())
{
return Response::json( ['status' => 'error', 'msg' => 'There was an error. I could not find what you were looking for.'] );
}
elseif ( ! Config::get('app.debug'))
{
return Response::view('errors.404', array(), 404);
}
});
From looking at your code - you seem to be duplicating the response class. I dont understand why you are doing all of that, when you can just do
return Response::view('error', $message, $statuscode);
anywhere in your application...
Edit: you could also do
App::abort(404);
And then catch the abort filter in your app. You can change the 404 to be any HTTP response code you want.

Can't read $this->post('username'); in rest server from input form rest client

Why $this->post('username') can not read input from rest client ?
In my controller for server :
function login_post(){
$data['username']=$this->post('username');
$data['password']=$this->post('password');
if ($this->get('cobak')==1) {
$cek = $this->model_user->ambilPengguna($data);
}
if ($cek) {
$this->response($cek, 200); // 200 being the HTTP response code}
else {
$this->response(array('error' => 'User could not be found'), 404);
}
}
My models :
public function ambilPengguna($data) {
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->where($data);
$query = $this->db->get();
return $query->num_rows();
}
And this is my client controller :
public function proses_login(){
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$cek = $this->rest->post('login/cobak/1/format/php/');
echo $cek;
}
The result from query is 5. It means read all record in database table
You send data by URL method you can send data instead as the following
for more information about URL method you can read this
$cek = $this->rest->post('login', $data, 'php');
you can recieve data in server by two ways
$this->post('username') or $this->input->post('username')
I think it may work
you can get more details from : Here

Resources