how to save data from Bootstrap Modal using Codeigniter? - php

I am trying to save data inserted from a modal. Now i have a view called users where i show the list of users.now if admin clicks on add more users it opens a bootstap modal where i have a field called no of users requested. So whatever value the admin fills that must be save into database. I am confused on how to save this.
Edited...................................................
After reseller logs in he can request more users to admin so i created that modal to request the users required so i want to store the number of users required by that reseller along with his/her key
My Controller is :
public function index ()
{
$usertype=$this->session->userdata('usertype');
if($usertype ==="reseller")
{
$key= $this->session->userdata('key');
$this->db->where("key",$this->session->userdata('key'));
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'reseller/user/index';
$this->load->view('reseller/_layout_main', $this->data);
}
else
{
$this->load->view('permission');
}
}
My view Is :
Request More Users
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add the number of users you want</h4>
</div>
<div class="modal-body">
<form id="loginForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">Number Of Users</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" id="spinnerInput" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Your question unclear but will give it ago. On your form you need to have form action if you do not have it then will not work. make sure also url helper is auto loaded.
Docs http://www.codeigniter.com/docs
Also would look into codeigniter form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
And form helper
http://www.codeigniter.com/user_guide/helpers/form_helper.html
<form action="<?php echo base_url('controller-name/function');?>" method="post" method="post">
You may need to use index.php in base_url();
<form action="<?php echo base_url('index.php/controller-name/function');?>">
View
Request More Users
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add the number of users you want</h4>
</div>
<div class="modal-body">
<form id="loginForm" method="post" class="form-horizontal" action="<?php echo base_url('controller-name/request');?>">
<div class="form-group">
<label class="col-xs-3 control-label">Number Of Users</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="username" id="spinnerInput" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Password</label>
<div class="col-xs-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
Model
class User_m extend CI_Model {
function request_user() {
$data = array(
'key' => $this->session->userdata('key'),
'total_user' => $this->get_total(), // create a column in table
'username' => $this->input->post('username')
);
$this->db->insert('table', $data);
}
function request_update_user() {
$data = array(
'total_user' => $this->get_total() // create a column in table
'username' => $this->input->post('username')
);
$this->db->where('key', $this->session->userdata('key'));
$this->db->update('table', $data);
}
function get() {
$this->db->where('key', $this->session->userdata('key'));
$query = $this->db->get('table');
return $query->result_array();
}
function get_total() {
$this->db->where('key', $this->session->userdata('key'));
$query = $this->db->get('table');
return $query->num_rows();
}
}
Controller
class Reseller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_m');
}
public function index () {
$usertype = $this->session->userdata('usertype');
if($usertype == "reseller") {
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'reseller/user/index';
$this->load->view('reseller/_layout_main', $this->data);
} else {
$this->load->view('permission');
}
}
public function request() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('modal_view');
} else {
$this->user_model->request_user();
redirect('your_controller');
}
}
}

Related

Laravel duplicate entries when reload page

I have a model ,a controller and a form for introducing entries to database.The problem is that refresing the page cause duplicate entries in database.How to resolv it?
loan.controller:
public function store(Request $request)
{ $id = Auth::id();
$loan=New loan;
$loan->cod_user=$id;
$loan->nume =$request->name;
$loan->data=$request->date;
$loan->durata=$request->period;
$loan->valoare_rata_luna=$request->month;
$loan->valoare_totala=$request->amount;
$loan->save();
return view('loans');
}
the form from loans view:
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="blacktext"><h3>My Loans:</h3></div>
</div>
<div class="col-md-4"></div>
<div class="col-md-2"></div>
<div class="col-md-2"><button type="button" class="btn btn-success" data-toggle="modal" data-target="#modal1">
<span class="glyphicon glyphicon-plus-sign"></span> Add Loan</button></div>
<div class="modal fade " id="modal1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Add Loan</h3>
</div>
<div class="modal-body text-right">
<form action="{{ route('loan.store') }}" method="POST">
<p class="al-left">
{{csrf_field()}}
<label for="date">Date:</label>
<input type = "date" name="date" placeholder="Date" id="date">
</p>
...
<p class="al-left">
<label for="amount">Amount:</label>
<input type = "number" name="amount" placeholder="0" id="amount">
</p>
<input type="submit" class="btn btn-sm btn-primary" name="submit" value="Add">
Just redirect to the route (the route which serves the view) instead of the view at the end of your store method:
public function store(Request $request)
{ $id = Auth::id();
$loan=New loan;
$loan->cod_user=$id;
$loan->nume =$request->name;
$loan->data=$request->date;
$loan->durata=$request->period;
$loan->valoare_rata_luna=$request->month;
$loan->valoare_totala=$request->amount;
$loan->save();
return redirect(route(('loans')); //asumming that you named a route as loans
}
Try to use
return redirect()-back();
It will work for sure.
POST still exists upon refresh .. what you can do is have a page separated from store function .. like this ..
ROUTE
Route::get('/loans', 'LoanController#viewLoanForm');
Route::post('/loans', 'LoanController#store');
LoanController
public function viewLoanForm()
{
return view('loan');
}
public function store(Request $request)
{
// process your input
return redirect('/loans');
}
I think you should change your return method like:
public function store(Request $request)
{ $id = Auth::id();
$loan=New loan;
$loan->cod_user=$id;
$loan->nume =$request->name;
$loan->data=$request->date;
$loan->durata=$request->period;
$loan->valoare_rata_luna=$request->month;
$loan->valoare_totala=$request->amount;
$loan->save();
return redirect()->route('loans');
}

How to create Drop down from database in Codeigniter

Sorry, i want the create Form input using drop down from database. but i've try to created and error like this.
My Code in controller
public function ajax_add()
{
$data = array(
'date_man_activity_ra' => $this->input->post('date_man_activity_ra',TRUE),
'dd_user' => $this->mymodel->dd_user(),
'user_selected' => $this->input->post('id_user') ? $this->input->post('id_user') : '',
'id_user' => $this->input->post('id_user',TRUE),
'note' => $this->input->post('note',TRUE),
);
$insert = $this->Man_activity->save($data);
echo json_encode(array("status" => TRUE));
}
and mymodel
public function dd_user()
{
// ambil data dari db
$this->db->order_by('id_user', 'asc');
$result = $this->db->get('ops_user');
// bikin array
// please select berikut ini merupakan tambahan saja agar saat pertama
// diload akan ditampilkan text please select.
$dd[''] = 'Please Select';
if ($result->num_rows() > 0) {
foreach ($result->result() as $row) {
// tentukan value (sebelah kiri) dan labelnya (sebelah kanan)
$dd[$row->id_user] = $row->username;
}
}
return $dd;
}
and my View
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">date_man_activity_ra</label>
<div class="col-md-9">
<input name="date_man_activity_ra" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Id User</label>
<div class="col-md-9">
<?php
$dd_user_attribute = 'class="form-control select2"';
echo form_dropdown('id_user', $dd_user, $user_selected, $dd_user_attribute);
?>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Note</label>
<div class="col-md-9">
<input name="note" placeholder="note" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
how to solve it? or Another ways?
Thank You
public function ajax_add()
{
$data = array(
'date_man_activity_ra' => $this->input->post('date_man_activity_ra',TRUE),
'dd_user' => $this->mymodel->dd_user(),
'user_selected' => $this->input->post('id_user') ? $this->input->post('id_user') : '',
'id_user' => $this->input->post('id_user',TRUE),
'note' => $this->input->post('note',TRUE),
);
$insert = $this->Man_activity->save($data);
// Load your view and pass the data that you use in dropdown
//echo json_encode(array("status" => TRUE)); // Remove it
}

HTML Bootstrap PHP connection error

I want to write log in code for my index.html ' s form and i wrote a giris-yap.php file which is at below. i cant access my php file browser get alert only like localhost is waiting .
i tried to put action method in my form's submit button but it was not usefull.
giris-yap.php
<?php
require "connect.inc.php";
require "core.inc.php";
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$mail=$_POST['exampleInputEmail1'];
$pass=$_POST['exampleInputPassword1'];
$password=md5($pass);
if($query_run=mysql_query("SELECT * FROM `users` WHERE `e-mail`= '".mysql_real_escape_string($mail)."' AND `sifre`='".mysql_real_escape_string($password)." ' ")){
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0){
echo 'Invalid';
}
else if($query_num_rows!=0){
$ad=mysql_result($query_run,0,'Ad');
$_SESSION['ad']=$ad;
$usersurname=mysql_result($query_run,0,'SoyAd');
$_SESSION['usersurname']=$usersurname;
$username=mysql_result($query_run,0,'e-mail');
$_SESSION['username']=$username;
header('Location: index.html');
}
}
else{
echo mysql_error();
}
}
else{echo 'error';}
/**
* Created by PhpStorm.
* User: bilsay
* Date: 21.05.2015
* Time: 10:35
*/
?>
index.html :
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="#giris-kontrol" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" value="Giriş">Giriş</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
cant access my php file
You need to update your action as described in the other answer: https://stackoverflow.com/a/30377560/482256.
Then, note that this code here:
require connect.inc.php;
require core.inc.php;
Is the equivalent of doing this:
require 'connectincphp';
require 'coreincphp';
When you don't use quotes, PHP looks for constants, and when it doesn't find those it will assume the string, so connect becomes "connect". The period concatenates, so it combines "connect" with "inc" and you get "connectinc", etc.
The require should be causing a 500 error...and possibly an empty page depending on what your error output settings are.
Your code translated to PDO and BCrypt, because I just can't "fix" code and leave it insecure:
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$pdo = new \PDO('mysql:dbname=dbName;host=localhost','username','password');
$mail = $_POST['exampleInputEmail1'];
$pass = $_POST['exampleInputPassword1'];
$userSql = $pdo->prepare("SELECT * FROM `users` WHERE `e-mail`=:email");
$userSql->execute(array('email'=>$mail));
$userData = $userSql->fetch(\PDO::FETCH_ASSOC);
if( $userData !== false && BCrypt::isValidPassword($pass, $userData['sifre']) ) {
$_SESSION['ad'] = $userData;
$_SESSION['usersurname'] = $userData['SoyAd'];
$_SESSION['username'] = $userData['username'];
header('Location: index.html');
}
else {
die("You have entered an invalid username or password");
}
}
else{
die("Username and Password must be submitted");
}
And your modified HTML. I fixed the action, turned your button into a real submit button, and added the name= attributes to your inputs:
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="giris-yap.php" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" value="1" class="btn btn-primary" id="submit"> Giriş Yap</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
And the BCrypt class you will need. However, use password_hash and password_verify if you have PHP >= 5.5.
class BCrypt {
public static function hash( $password, $cost=12 ) {
$base64 = base64_encode(openssl_random_pseudo_bytes(17));
$salt = str_replace('+','.',substr($base64,0,22));
$cost = str_pad($cost,2,'0',STR_PAD_LEFT);
$algo = version_compare(phpversion(),'5.3.7') >= 0 ? '2y' : '2a';
$prefix = "\${$algo}\${$cost}\${$salt}";
return crypt($password, $prefix);
}
public static function isValidPassword( $password, $storedHash ) {
$newHash = crypt( $password, $storedHash );
return self::areHashesEqual($newHash,$storedHash);
}
private static function areHashesEqual( $hash1, $hash2 ) {
$length1 = strlen($hash1);
$length2 = strlen($hash2);
$diff = $length1 ^ $length2;
for($i = 0; $i < $length1 && $i < $length2; $i++) {
$diff |= ord($hash1[$i]) ^ ord($hash2[$i]);
}
return $diff === 0;
}
}
change action..
<form action="giris-yap.php" method="POST">
then change a link in your modal-footer
<button type="submit" value="Giriş Yap" class="btn btn-primary" id="submit" />

Reload Bootstrap Modal on PHP variable not valid

Having some problems with the error handling of a bootstrap modal. In the modal I have two inputs (both are required). I want to be able to display a simple "required" message if the form is submitted without one of the fields populated.
I tried doing this with PHP and it works in a page by itself, but when I put it in a modal the modal closes on submit and then if you re-open the modal you see the error messages. I really want the modal to stay open or re-open if the input fields are not valid when the user submits.
Any help would be appreciated! Thanks!
HTML (Start of the modal):
<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add a vCenter</h4>
</div>
<div class="modal-body">
PHP (To graph the input and report any errors):
if ( !empty($_POST)) {
// keep track validation errors
$vcenternameError = null;
$vcenterownerError = null;
// keep track post values
$vcentername = $_POST['vcentername'];
$vcenterowner = $_POST['vcenterowner'];
// validate input
$valid = true;
if (empty($vcentername)) {
$vcenternameError = 'Please enter vCenter Name';
$valid = false;
}
if (empty($vcenterowner)) {
$vcenterownerError = 'Please select vCenter Owner';
$valid = false;
}
// insert data
if ($valid) {
$sql = "INSERT INTO ";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
header("Location: index.php");
}
}
?>
HTML (the rest of the modal):
<div class="panel-body">
<form class="form-horizontal" action="index.php" method="post">
<div class="<?php echo !empty($vcenternameError)?'error':'';?> form-group">
<div class="alert alert-warning">
Please input the FQDN of the vCenter and select an owner.
</div>
<label class="control-label">vCenter Name</label>
<div class="controls">
<input name="vcentername" type="text" placeholder="vCenter Name" value="<?php echo !empty($vcentername)?$vcentername:'';?>" class="form-control">
<?php if (!empty($vcenternameError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenternameError;?>
</div>
<?php endif; ?>
</div>
</div>
<div class="<?php echo !empty($vcenterownerError)?'error':'';?> form-group">
<label class="control-label">vCenter Owner</label>
<div class="controls">
<div class="btn-group" data-toggle="button" role="group" aria-label="...">
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team1"> Team1
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team2"> Team2
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team3"> Team3
</label>
</div>
<?php if (!empty($vcenterownerError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenterownerError;?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button type="submit" class="btn btn-success">Add</button>
<a class="btn btn-default" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>
You can use jQuery to open the modal again if the modal contains errors when the page loads:
var modal = $('#createModal');
if(modal.find('div.alert-warning').length)
modal.modal();
But for the best user experience, you should call your PHP script with an ajax request: http://api.jquery.com/jquery.ajax/

PHP login form within Bootstrap modal not working

I have created a login form within a Bootstrap modal but when the correct information is entered the user is shown the same page but with the modal closed i.e. not redirected to viewDashboard.php.
Code
<!-- Modal -->
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="ModalLabel">Login to Portal</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="" method="post">
<fieldset>
<div class="form-group">
<label for="inputID" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputID" name="user" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<?php
include("core/connection.php");
if($conn AND !empty($_POST)){
$stid = oci_parse($conn, "SELECT * FROM Customers WHERE Customers.CustomerNo = ".$_POST['user']."");
oci_execute($stid);
$count = oci_fetch_all($stid, $res);
if ($count > 0) {
session_start();
$_SESSION['account'] = $_POST['account'];
header("Location: viewDashboard.php");
}
oci_free_statement($stid);
oci_close($conn);
}
?>
</div>
If your user is correctly authenticated you should create a new session for him
session_start();
$_SESSION['user'] = array('id' => '...', name => '...', ...);
The information in the session can then be used in your secured section to check if the user is connected
session_start();
if (!isset($_SESSION['user']) {
// redirect to login page
}
Finally the redirection should be made before any information is sent to the client using:
// once logged
header('location:viewDashboard.php');
// on logout or if trying to access secured section
header('location:login.php');
EDIT to reflect the first 2 comments :
Your page should be structured like this:
//login.php
<?php
if (isset($_POST)) {
// login check
if ($isLogged) {
// session creation
header('location:...');
}
}
?>
<html>
<head>...</head>
<body>
...
<!-- Your modal box -->
</body>
</html>
If you want to re-open your modal box upon unsuccessful login, you should use your PHP to set the value of a flag (like !$isLogged you set a flag in your JS). If the flag is set to true, you trigger the modal box with Twitter's boostrap js.
References :
Sessions
Headers

Categories