(The POST method is not supported for this route. Supported methods: GET, HEAD.) laravel solution? - laravel-5.8

I'm new to laravel and I want to submit a registration user form that when clicked, data will be sent to my database (which is already configured) and the page will be directed to the login page but when I click submit button laravel, it says
"The POST method is not supported for this route. Supported methods: GET, HEAD."
I've searched a lot but i am clueless as i don't understand what to do.
My registration view
<?php
// Include config file
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: /");
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>
My Routes
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/','LoginController#login');
Route::get('registration','LoginController#registration');
Route::get('welcome','LoginController#welcome');
My Controller (Not sure if this could be the source of the problem but....)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function login()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function welcome()
{
return view('welcome');
}
}
And last but not least my login file which i don't think is necessary but I'll just share as well.
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: /welcome");
exit;
}
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: /welcome");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? Sign up now.</p>
</form>
</div>
</body>
</html>

Related

Error: page requested not found codeigniter

Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.

Redirect customer to product page from where customer logged in to website Magento 2

In Magento 2, I have a custom login form in Header.
If a customer is on the product page for eg :
http://www.testwebsite.com/catalog/product/view/id/10
and login from header form then customer should redirect to the same product page instead of Customer Dashboard.
I have tried plugin code from this link.
Below is my custom header form code -
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath('/'); // Change this to what you want
return $result;
}
}
I want to redirect the customer to $currenturl. Link tutorial can be able to redirect to the home page. Please suggest what needs to be done to achieve to redirect the customer to the current page.
Try the below:
Header Login Form :-
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<input type="hidden" name='referer' value="<?php echo $currenturl ?>">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code : -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
) {
$this->request = $request;
}
public function getPostReferer()
{
return $this->request->getPostValue('referer');
}
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath($this->getPostReferer());
return $result;
}
}
Please try with the following code I have set the current url to the instant of $resultRedirect like this : $resultRedirect->setUrl($currenturl);
<?php
namespace Vendor\Module\Controller\Account;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
public function execute() {
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$sku = '24-MB01'; //Edit as per your product sku
$_product = $this->productRepository->get($sku);
$currenturl = $_product->getProductUrl();
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __(
'This account is not confirmed.' .
' Click here to resend confirmation email.', $value
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (\Exception $e) {
$this->messageManager->addError(__('Invalid login or password.'));
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
}
If you have a plugin that receives the Magento\Customer\Controller\Account\LoginPost object you could get the referer URL like : $subject->_redirect->getRefererUrl(). Then return this URL
$productURL = $subject->_url->getUrl($subject->_redirect->getRefererUrl());
return $subject->_redirect($productURL);
I'm not 100% sure if this URL will actually be the URL you want but worth a try.

Can't log in to admin dashboard

My password and username are correct, but I can't login to admin. Is there anything wrong with my controller?
This is my model:
class login_model extends CI_Model{
function cek($username, $password){
$this->db->where("username", $username);
$this->db->where("password", $password);
return $this->db->get("user_admin");
}
function getLoginData($usr, $psw){
$u = $usr;
$p = md5($psw);
$q_cek_login = $this->db->get_where('user_admin', array('username' => $u, 'password' => $p));
if(count($q_cek_login->result()) > 0){
foreach($q_cek_login->result() as $qck){
foreach($q_cek_login->result() as $qad){
$sess_data['logged_in'] = TRUE;
$sess_data['id'] = $qad->id;
$sess_data['username'] = $qad->username;
$sess_data['password'] = $qad->password;
$sess_data['email'] = $qad->email;
$sess_data['level'] = $qad->level;
$this->session->set_userdata($sess_data);
}
redirect('welcome_message');
}
}else{
$this->session->set_flashdata('result_login'. 'username dan password salah');
header('location: '. base_url(). 'login');
}
}
}
This is my controller:
class login extends CI_Controller {
function _construct(){
parent::_construct();
if($this->session->userdata('username')){
redirect(base_url('welcome_message'));
}
$this->load->model(array('login_model'));
}
function index(){
$this->load->view('login');
}
function proses(){
$this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
if($this->form_validation->run() == FALSE){
$this->load->view('login');
}else{
$usr = $this->input->post('username');
$psw = $this->input->post('password');
$u = $usr;
$p = md5($psw);
$cek = $this->login_model->cek($u, $p);
if($cek->num_rows() > 0 ){
foreach($cek->result() as $qad){
$sess_data['id'] = $qad->id;
$sess_data['email'] = $qad->email;
$sess_data['username'] = $qad->username;
$sess_data['level']=$qad->level;
$this->session->set_userdata($sess_data);
}
$this->session->set_flashdata('success', 'login berhasil');
redirect(base_url('/'));
}else{
$this->session->set_flashdata('result_login', 'username dan password yang anda masukkan salah');
redirect(base_url('login'));
}
}
}
My view:
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="<?php echo base_url('login/proses'); ?>" method="post">
<?php if (validation_errors() || $this->session->flashdata('result_login')) { ?>
<div class="alert alert-danger animated fadeInDown" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Peringatan!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" id="username" name="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
Register a new admin
</div>
When I try to log in, I always get this error:
I don't see anything strikingly wrong with your code.
Well you are obviously hitting your last nested else which means for some reason this statement $cek->num_rows() > 0 is evaluating to false.
I assume that you are entering a proper and existing username + password combination. But to troubleshoot you can after $p = md5($psw); do:
echo 'hashed password: ' . $p . '<br>username: ' . $u; exit;
and see if the username and hashed password match something in the database, if not, you have your answer. My best guess is that you perhaps didn't store a hashed password and only plain-text one.
As a side note you should move all of your redirects and flashdata out of your model. Models should only return or throw Exceptions.

How to put Session data to textbox in Codeigniter

I'm the newbie in Codeigniter. I put the textbox values to session and go to next page and when i click the back button on 2nd page, then the 1st page data should be still in textbox. How can I do that? Please help me.
Controller code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index(){
$this->load->view('welcome_message');
}
public function page1(){
$this->session->set_userdata('page1',$this->input->get());
$this->config->load('config');
$this->config->set_item('sess_expiration', '60');
$this->load->view('pg2');
}
public function page2(){
$this->session->set_userdata('page2',$this->input->get());
$this->config->load('config');
$this->config->set_item('sess_expiration', '60');
$this->load->view('pg3');
}
public function page3(){
$this->config->load('config');
$this->config->set_item('sess_expiration', '60');
$sess_data=$this->session->userdata();
$ses_key = key($sess_data);
if (empty($this->session->userdata("page1")))
{
echo "Session has been Expired~!";
$this->session->unset_userdata('page1');
$this->session->unset_userdata('page2');
//redirect(site_url(),'refresh');
}
else
{
$q1 = ($sess_data['page1']);
$q2 = ($sess_data['page2']);
$result1 = '';
$result2 = '';
$result3 = '';
$result4 = '';
$result5 = '';
$result6 = '';
$result7 = '';
$result8 = '';
for ($i = 0; $i < count($q1); $i++)
{
$key=key($q1);
$val=$q1[$key];
if ($val<> ' ')
{
if ($key === 'input1')
{
$result1 = $val;
//echo $result1;
}
else if ($key === 'input2')
{
$result2 = $val;
//echo $result2;
}
else if ($key === 'input3')
{
$result3 = $val;
//echo $result3;
}
else
{
$result4 = $val;
//echo $result4;
}
echo $key ." = ". $val ." <br> ";
}
next($q1);
}
for ($i = 0; $i < count($q2); $i++)
{
$key=key($q2);
$val=$q2[$key];
if ($val<> ' ')
{
if ($key === 'input5')
{
$result5 = $val;
//echo $result5;
}
else if ($key === 'input6')
{
$result6 = $val;
//echo $result6;
}
else if ($key === 'input7')
{
$result7 = $val;
//echo $result7;
}
else
{
$result8 = $val;
//echo $result8;
}
echo " <br> <br> " . $key ." = ". $val ." <br> ";
}
next($q2);
}
//$this->testing_model->add_data('sess_table',['val'=>$result1,'val2'=>$result2]);
$this->testing_model->add_data('user_table',['id'=>"default", 'text2'=>$result1, 'text3'=>$result2, 'text4'=>$result3, 'text5'=>$result4]);
$this->testing_model->add_data('sess_table',['id'=>"default", 'val'=>$result5, 'val2'=>$result6, 'val3'=>$result7, 'val4'=>$result8]);
echo "Successfully Saved to Database!";
$this->session->unset_userdata('page1');
$this->session->unset_userdata('page2');
//$querydata=$this->testing_model->query('select * from sess_table');
//print "<pre/>";
// print_r($querydata);
// foreach ($querydata as $key => $value) {
// print_r(json_decode($value->val,true));
// print_r(json_decode($value->val2,true));
// // echo json_decode($value->val.' ---- '.$value->val2;
// }
}
}
}
View 1:
<!DOCTYPE html>
<html lang="en">
</head>
<body>
page 1
<form method="get" action="<?= base_url('welcome/page1') ?>">
input 1 <input name="input1" type="text"/> <br/>
input 2 <input name="input2" type="text"/> <br/>
input 3 <input name="input3" type="text"/> <br/>
input 4 <input name="input4" type="text"/> <br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
View 2:
<!DOCTYPE html>
<html lang="en">
</head>
<body>
page 2
<form method="get" action="<?= base_url('welcome/page2') ?>">
input 1 <input name="input5" type="text" /> <br/>
input 2 <input name="input6" type="text" /> <br/>
input 3 <input name="input7" type="text" /> <br/>
input 4 <input name="input8" type="text" /> <br/>
<input type="submit" value="go"/>
<a type="button" href="<?= base_url('welcome/page2') ?>">Back</a>
</form>
</body>
View 3:
<html>
<head>
<title></title>
</head>
<body>
<form method="get" action="<?= base_url('welcome/page3') ?>">
<input type="submit" value="Save"/>
<a type="button" href="<?= base_url('welcome/page1') ?>">Back</a>
</form>
</body>
</html>
Load library session in construct
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
Open your autoload.php in applications/config/autoload.php
$autoload['libraries'] = array('session');
The session data is the least of your problems.
First off, $this->load->view('pg2'); does not call your other functions in your controller, it loads a view named 'pg2'. In your question you didn't show the names of your views but if 'View 1' is a file named pg1.php in the /views folder, your controller function could look like this:
public function pg1() {
$this->session->set_userdata('page1',$this->input->get());
$this->load->view('pg1');
}
And then you have to learn how to pass data to display in views too... Try to read up on the docs, for example here's the page on how views work: https://www.codeigniter.com/user_guide/general/views.html

keep all selected values after submit

I'm stuck with this script I'm using:
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="includes/css/style.css" type="text/css" rel="stylesheet" />
<link href="includes/css/wt-gallery.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="includes/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="includes/js/configuratie.js"></script>
<script type="text/javascript" src="includes/js/jquery.wt-gallery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#wait_1').hide();
$('#drop_1').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func: "drop_1",
drop_var: $('#drop_1').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
$('#wait_2').hide();
$('#drop_2').change(function(){
$('#wait_2').show();
$('#result_2').hide();
$.get("func.php", {
func: "drop_2",
drop_var: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout("finishAjax2('result_2', '"+escape(response)+"')", 400);
});
return false;
});
$('#wait_3').hide();
$('#drop_3').change(function(){
$('#wait_3').show();
$('#result_3').hide();
$.get("func.php", {
func: "drop_3",
drop_var: $('#drop_3').val()
}, function(response){
$('#result_3').fadeOut();
setTimeout("finishAjax3('result_3', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#wait_1').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax2(id, response) {
$('#wait_2').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax3(id, response) {
$('#wait_3').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_three(id, response) {
$('#wait_2').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_four(id, response) {
$('#wait_3').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_five(id, response) {
$('#wait_4').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
</head>
<?php
$website = "it";
// configuratie file en db connect
include "includes/inc/config.inc.php";
include('db.php');
include_once "class/slider.class.php";
include('func.php');
$slideralbum = new slideralbum($dbo);
$sliders = $slideralbum->getSliderItems($website);
?>
<body>
<p>
<form name="product" action="" method="post">
<select name="drop_1" id="drop_1">
<option value="" selected="selected" disabled="disabled">Selecteer Merk</option>
<?php getTierOne(); ?>
</select>
<span id="wait_1" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_1" style="display: none;"></span>
<span id="wait_2" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_2" style="display: none;"></span>
<span id="wait_3" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_3" style="display: none;"></span>
<span id="wait_4" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_4" style="display: none;"></span>
<INPUT TYPE="button" VALUE="Refresh" onclick='location.reload()'>
</form>
</p>
<p>
<?php if(isset($_POST['submit'])){
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];
$drop_4 = $_POST['drop_4'];
$drop_5 = $_POST['drop_5'];
?>
<table border="1" bordercolor="#B5B5B5" style="background-color:#FFFFFF" width="250" cellpadding="3" cellspacing="3">
<tr>
<td>Merk:</td>
<td><?php echo $drop;?></td>
</tr>
<tr>
<td>Model:</td>
<td><?php echo $drop_2;?></td>
</tr>
<tr>
<td>Bouwjaar:</td>
<td><?php echo $drop_3;?></td>
</tr>
<tr>
<td>Kleur:</td>
<td><?php echo $drop_4;?></td>
</tr>
</table>
<?php
}
?>
<div id="banner-block"> <!-- Begin of Slideshow -->
<div class="container">
<div class="wt-gallery" style="width:920px; height:375px;">
<div class="main-screen">
<?php if(isset($_POST['submit'])){
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];
$drop_4 = $_POST['drop_4'];
$drop_5 = $_POST['drop_5'];
?>
<img src="images/<?php echo $drop_5;?>" alt="<?php echo $drop_5;?>" width="920" height="360"/>
<?php
}
?>
<noscript>
<!-- placeholder image when javascript is off -->
<img src="../images/triworks_abstract27.jpg" alt=""/>
</noscript>
</div>
<div class="cpanel">
<div class="thumbs-back"></div>
<div class="thumbnails">
<ul>
<?php $sliders = $slideralbum->getSliderItems($website, NULL);
foreach($sliders as $slider){
?>
<li effect="none">
<div>
<a href="<?php echo $slider->slider_img; ?>" height="360" width="720" alt="<?php echo $slider->slider_img; ?>" />
<img src="<?php echo $slider->slider_tmb; ?>" height="70" width="125" alt="<?php echo $slider->slider_tmb; ?>" />
</a>
</div>
<div class="data">
</div>
</li>
<?php
}
?>
</ul>
</div>
<div class="thumbs-fwd"></div>
</div>
</div>
</div>
</div>
</body>
</html>
func.php
<?php
//**************************************
// Page load dropdown results //
//**************************************
function getTierOne()
{
$result = mysql_query("SELECT DISTINCT make FROM vehicles ORDER BY make ASC")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
?>
<option value="<?php echo $tier['make'];?>"<?php echo (isset($_POST['drop_1']) && $_POST['drop_1'] == $tier['make']) ? ' selected="selected"' : '' ; ?>><?php echo $tier['make'];?></option>
<?php
}
}
//**************************************
// First selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_1" ) {
drop_1($_GET['drop_var']);
}
function drop_1($drop_var)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT model FROM vehicles WHERE make='$drop_var' ORDER BY model")
or die(mysql_error());
echo '<select name="drop_2" id="drop_2">
<option value=" " disabled="disabled" selected="selected">Selecteer Model</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['model'].'">'.$drop_2['model'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_2').hide();
$('#drop_2').change(function(){
$('#wait_2').show();
$('#result_2').hide();
$.get(\"func.php\", {
func: \"drop_2\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout(\"finishAjax_tier_three('result_2', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Second selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_2" ) {
drop_2($_GET['drop_var'], $_GET['drop_var2']);
}
function drop_2($drop_var, $drop_var2)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT year FROM vehicles WHERE make='$drop_var' AND model='$drop_var2'")
or die(mysql_error());
echo '<select name="drop_3" id="drop_3">
<option value=" " disabled="disabled" selected="selected">Selecteer Jaar</option>';
while($drop_3 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_3['year'].'">'.$drop_3['year'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_3').hide();
$('#drop_3').change(function(){
$('#wait_3').show();
$('#result_3').hide();
$.get(\"func.php\", {
func: \"drop_3\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val(),
drop_var3: $('#drop_3').val()
}, function(response){
$('#result_3').fadeOut();
setTimeout(\"finishAjax_tier_four('result_3', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Third selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_3" ) {
drop_3($_GET['drop_var'], $_GET['drop_var2'], $_GET['drop_var3']);
}
function drop_3($drop_var, $drop_var2, $drop_var3)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT color FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3'")
or die(mysql_error());
echo '<select name="drop_4" id="drop_4">
<option value=" " disabled="disabled" selected="selected">Selecteer Kleur</option>';
while($drop_4 = mysql_fetch_array( $result ))
{
if ($drop_4['color'] != "") {
echo '<option value="'.$drop_4['color'].'">'.$drop_4['color'].'</option>';
}
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_4').hide();
$('#drop_4').change(function(){
$('#wait_4').show();
$('#result_4').hide();
$.get(\"func.php\", {
func: \"drop_4\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val(),
drop_var3: $('#drop_3').val(),
drop_var4: $('#drop_4').val()
}, function(response){
$('#result_4').fadeOut();
setTimeout(\"finishAjax_tier_five('result_4', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Fourth selection results //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_4" ) {
drop_4($_GET['drop_var'], $_GET['drop_var2'], $_GET['drop_var3'], $_GET['drop_var4']);
}
function drop_4($drop_var, $drop_var2, $drop_var3, $drop_var4)
{
include_once('db.php');
$result = mysql_query("SELECT * FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3' AND color='$drop_var4'")
or die(mysql_error());
while($drop_5 = mysql_fetch_array( $result ))
{
if ($drop_5['img'] != "") {
echo '<input type="checkbox" name="drop_5" id="drop_5" style="display:none;" checked value="'.$drop_5['img'].'"/>';
}
}
echo '<input type="submit" name="submit" value="Submit" />';
}
?>
After I selected all my dropdown items and press submit it is working good but all the selected values are gone...
If you want to change color you have to go to the whole dropdown list again. Is it possible to keep all the selected values after submit?
Thanks in advance
Kind Regards
Joep
You are using GET requests to display each dropdown list in turn, and then using a POST request to submit your completed form. You should make sure that all the dropdowns are displayed after the POST request.
In index.php, I think you could try something like that :
<span id="result_1" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_1($_POST['drop_1']);
}
?>
</span>
...
<span id="result_2" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_2($_POST['drop_1'], $_POST['drop_2']);
}
?>
</span>
...
<span id="result_3" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_3($_POST['drop_1'], $_POST['drop_2'], $_POST['drop_3']);
}
?>
</span>
etc...
Anyway, the idea is to reuse the functions that build your dropdowns, based on the values in the $_POST.

Resources