keep all selected values after submit - form-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.

Related

Can't get data from request with ajax

Trying to get data from a database request with ajax
As you can seen bellow. Codes are basic ajax and sql request codes, there is no complicated things. But my result is allways null.
I need help, thanks
PS: Sorry for my english
Ajax code
$(document).ready(function(){
$("#ligue").change(function(){
var Ligue_Name=$(this).val();
$.ajax({
type: "POST",
url: "pages/test.php",
data: {Ligue_Name:Ligue_Name},
cache: false,
success: function(html){
$("#club").html(html);
}
});
});
});
test.php
<?php
global $db;
$output = '';
$req = $db->query(
"SELECT * FROM club WHERE Ligue_Name LIKE ".$_POST['Ligue_Name']."
");
$output .= '<option value="" disabled selected>Select Ligue</option>';
if(mysqli_num_rows($req)>0){
while ($row = mysqli_fetch_array($req)) {
$output .= '<option value="'.$_POST["club"].'">'.$row["club"].'</option>';
}
}
echo $output;
?>
Your HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="club"></div><br />
<input type="text" id="ligue" >
<button type="button" id="addline" onclick="league();">+</button>
<script>
function league(){
var Ligue_Name=$("#ligue").val();
$.ajax({
type: "POST",
url: "pages/test.php",
data: {Ligue_Name:Ligue_Name},
cache: false,
success: function(html){
$("#club").html(html);
}
});
};
</script>
</body>
</html>
Your test.php,
<?php
global $db;
$output = '';
$req = $db->query(
"SELECT * FROM club WHERE Ligue_Name LIKE ".$_POST['Ligue_Name']."
");
$output .= '<option value="" disabled selected>Select Ligue</option>';
if(mysqli_num_rows($req)>0){
while ($row = mysqli_fetch_array($req)) {
$output .= '<option value="Testing">'.$row["club"].'</option>';
}
}
echo $output;
?>
Test.php
if($_POST["ligue"]){
global $db;
$output = '';
$req = $db->query(
"SELECT * FROM club WHERE Ligue_Name LIKE ".$_POST['Ligue_Name']."
");
$output .= '<option value="" disabled selected>Select Ligue</option>';
if(mysqli_num_rows($req)>0){
while ($row = mysqli_fetch_array($req)) {
$output .= '<option value="'.$_POST["name"].'">'.$row["name"].'</option>';
}
}
echo $output;
}
my.html
<div class="input-group mb-3">
<select class="custom-select" id="ligue" name="ligue">
<option selected disabled>Selectionnez votre ligue</option>
<?
$clubs = getClub();
foreach ($clubs as $club) {
?>
<option value="<?php echo $club->Ligue_Name ?>"><?php echo $club->Ligue_Name ?></option>
<?
}
?>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="club">Club</label>
</div>
<select class="custom-select" id="club" name="club" required>
</select>
</div>
<script>
$(document).ready(function(){
$("#ligue").change(function(){
var Ligue_Name=$(this).val();
$.ajax({
type: "POST",
url: "pages/test.php",
data: {Ligue_Name:Ligue_Name},
cache: false,
success: function(html){
$("#club").html(html);
}
});
});
});
</script>

Codeigniter Repotrs page problem with dates

I am developing a project using Codeigniter framework and in the reports page i need to have a form that has datatables structure so i can generate reports by day,month and year. but i dont know how to use datatables.
i have tried to add code like for example where it was written Y-m i added d-m-y but it doesn't work
Reports Controller:
defined('BASEPATH') OR exit('No direct script access allowed');
class Reports extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->data['page_title'] = 'Stores';
$this->load->model('model_reports');
}
/*
* It redirects to the report page
* and based on the year, all the orders data are fetch from the database.
*/
public function index()
{
if(!in_array('viewReports', $this->permission)) {
redirect('dashboard', 'refresh');
}
$today_year = date('Y');
if($this->input->post('select_year')) {
$today_year = $this->input->post('select_year');
}
$parking_data = $this->model_reports->getOrderData($today_year);
$this->data['report_years'] = $this->model_reports->getOrderYear();
$final_parking_data = array();
foreach ($parking_data as $k => $v) {
if(count($v) > 1) {
$total_amount_earned = array();
foreach ($v as $k2 => $v2) {
if($v2) {
$total_amount_earned[] = $v2['net_amount'];
}
}
$final_parking_data[$k] = array_sum($total_amount_earned);
}
else {
$final_parking_data[$k] = 0;
}
}
$this->data['selected_year'] = $today_year;
$this->data['company_currency'] = $this->company_currency();
$this->data['results'] = $final_parking_data;
$this->render_template('reports/index', $this->data);
}
}
**Reports Model:**
<?php
class Model_reports extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/*getting the total months*/
private function months()
{
return array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
}
/* getting the year of the orders */
public function getOrderYear()
{
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$return_data = array();
foreach ($result as $k => $v) {
$date = date('Y', $v['date_time']);
$return_data[] = $date;
}
$return_data = array_unique($return_data);
return $return_data;
}
// getting the order reports based on the year and moths
public function getOrderData($year)
{
if($year) {
$months = $this->months();
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$final_data = array();
foreach ($months as $month_k => $month_y) {
$get_mon_year = $year.'-'.$month_y;
$final_data[$get_mon_year][] = '';
foreach ($result as $k => $v) {
$month_year = date('Y-m', $v['date_time']);
if($get_mon_year == $month_year) {
$final_data[$get_mon_year][] = $v;
}
}
}
return $final_data;
}
}
}
**View index**
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Reports
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li class="active">Reports</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-md-12 col-xs-12">
<form class="form-inline" action="<?php echo base_url('reports/') ?>" method="POST">
<div class="form-group">
<label for="date">Year</label>
<select class="form-control" name="select_year" id="select_year">
<?php foreach ($report_years as $key => $value): ?>
<option value="<?php echo $value ?>" <?php if($value == $selected_year) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php endforeach ?>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<br /> <br />
<div class="col-md-12 col-xs-12">
<?php if($this->session->flashdata('success')): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php elseif($this->session->flashdata('error')): ?>
<div class="alert alert-error alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php endif; ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">Total - Report</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="chart">
<canvas id="barChart" style="height:250px"></canvas>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Total Paid Orders - Report Data</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="datatables" class="table table-bordered table-striped">
<thead>
<tr>
<th>Month - Year</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $k => $v): ?>
<tr>
<td><?php echo $k; ?></td>
<td><?php
echo $company_currency .' ' . $v;
//echo $v;
?></td>
</tr>
<?php endforeach ?>
</tbody>
<tbody>
<tr>
<th>Total Amount</th>
<th>
<?php //echo $company_currency . ' ' . array_sum($parking_data); ?>
<?php echo array_sum($results); ?>
</th>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- col-md-12 -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<script type="text/javascript">
$(document).ready(function() {
$("#reportNav").addClass('active');
});
var report_data = <?php echo '[' . implode(',', $results) . ']'; ?>;
$(function () {
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
var areaChartData = {
labels : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [
{
label : 'Electronics',
fillColor : 'rgba(210, 214, 222, 1)',
strokeColor : 'rgba(210, 214, 222, 1)',
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : report_data
}
]
}
//-------------
//- BAR CHART -
//-------------
var barChartCanvas = $('#barChart').get(0).getContext('2d')
var barChart = new Chart(barChartCanvas)
var barChartData = areaChartData
barChartData.datasets[0].fillColor = '#00a65a';
barChartData.datasets[0].strokeColor = '#00a65a';
barChartData.datasets[0].pointColor = '#00a65a';
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines : true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to make the chart responsive
responsive : true,
maintainAspectRatio : true
}
barChartOptions.datasetFill = false
barChart.Bar(barChartData, barChartOptions)
})
</script>

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

I want bootstrap-datetimepicker only Year and Month

Now, Bootstrap datetimepicker viewed YYYY-DD-MM format.
But, I want only YYYY-DD format.
For example, Like the picture above.
Now Source.
Also it did not resolve to remove the DD to the source.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="col-md-5">
<label style="margin-top: 8px;margin-left: 33px; white-space:nowrap;">datetimepicker</label>
</div>
<div class="col-md-7">
<input class="form-control" type="text" name="daterange" value='<?php if(isset($_GET['to']) && $_GET['to'] != '') { echo #$_GET['to']." - ".#$_GET['from']; } ?>' />
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(function() {
$('input[name="daterange"]').daterangepicker({
<?php if(isset($_GET['to']) && $_GET['to'] != '') { ?>startDate:'<?php echo #$_GET['to']; ?>',<?php } ?>
<?php if(isset($_GET['to']) && $_GET['to'] != '') { ?>endDate:'<?php echo #$_GET['from']; ?>',<?php } ?>
timePicker: false,
timePicker24Hour: false,
format: 'YYYY-MM-DD'
}, function(start, end)
{
location.href = "/Driving/drivingHistoryList?to="+start.format('YYYY-MM-DD')+"&from="+end.format('YYYY-MM-DD')+"<?php echo "&userid=".#$_GET['userid']."&carid=".#$_GET['carid']."&goal=".#$_GET['goal']."&order=".#$_GET['order']."&order_type=".#$_GET['order_type']."&page=".#$_GET['page']."&count=".#$_GET['count']; ?>";
});
});
</script>
Try this.
$('input[name="daterange"]').datepicker( {
format: "mm-yyyy",
viewMode: "months",
minViewMode: "months"
});
Try this
$("#datepicker").datepicker( {
format: "mm-yyyy" // yyyy-mm
});
Bootstrap DatePicker format - bootstrap-datepicker.readthedocs.io
Set 'viewMode' and 'format'. Try
$('input[name="daterange"]').datetimepicker({
<?php if(isset($_GET['to']) && $_GET['to'] != '') { ?>startDate:'<?php echo #$_GET['to']; ?>',<?php } ?>
<?php if(isset($_GET['to']) && $_GET['to'] != '') { ?>endDate:'<?php echo #$_GET['from']; ?>',<?php } ?>
viewMode: 'years',
format: 'MM/YYYY'
}

How to use AJAX to populate state list depending on Country list?

I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box
<input type="text" name="othstate" value="" class="textBox">
The form
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
The javascript
<script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.
jQuery example below:
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with
if (countryId == 233 || countryId == 234) {
/* Ajax state population here */
dropdownId.display = 'block';
textEntryId.display = 'none';
}
else {
textEntryId.display = 'block';
dropdownId.display = 'none';
}
(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.
JQuery is all well and good, but I wouldn't introduce it just to solve this problem.
EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</script>
<select style="background-color: #ffffa0" name="country" id=country >
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">
As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See
here.
I also eliminated the onchange event which is being replaced by the 'change()` jquery function.
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "ajaxServer.jsp",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
<table>
<tr>
<td> <label>Country:</label></td>
<td> <select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
</tr>
<tr><td >
<label>States:</label></td>
<td> <select id="response">
<option>Select State</option>
</select>
</td></tr>
</table>
</form>
</body>
</html>
**ajaxServer.jsp**
<option>Select State</option>
<%
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+india[i]+"</option>");
}
}
else if(count.equals("usa"))
{
for(int i=0;i<usa.length;i++)
{
out.print("<option>"+usa[i]+"</option>");
}
}
else if(count.equals("uk"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+uk[i]+"</option>");
}
}
%>
VK API just select country , get it id and select city from
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var _getCountry = function() {
$j.ajax({
url: "http://api.vk.com/method/database.getCountries",
data: {
'v': 5.5,
'need_all': 0,
'code' : 'RU,UA,BY,KZ,KG,LV,EE'
// 'count': 10
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each country");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
country_options.push(newOption);
});
document.getElementById('countrylist').innerHTML = country_options;
}
});
}
var _getCity = function(country_id) {
$j.ajax({
url: "http://api.vk.com/method/database.getCities",
data: {
'v': 5.61,
'need_all': 0,
'country_id': country_id
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each city");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
city_options.push(newOption);
});
document.getElementById('citylist').innerHTML = city_options;
}
});
}
var city_options = [];
var country_options = [];
$j(document).ready(function () {
_getCountry();
$j('#country').on('input',function() {
var opt = $j('option[value="'+$j(this).val()+'"]');
var countryid = opt.attr('id');
_getCity(countryid);
});
});
</script>
<div class="form-group">
<label class="col-lg-4 control-label">Страна:</label>
<div class="col-lg-8">
<div class="controls">
<input name="country" list="countrylist" id="country" class="form-control" />
<datalist id="countrylist">
</datalist>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Город:</label>
<div class="col-lg-8">
<input name="city" list="citylist" id="city" class="form-control"/>
<datalist id="citylist">
</datalist>
</div>
</div>
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db( 'testajax' );
?>
/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
include('con.php');
?>
<form>
<div class="frmDronpDown">
<div class="row">
<table><tr><td><label>Country:</label><br/>
<select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct country FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
<?php
}
?>
</select> </td>
<td>
<label>Phone:</label><br/>
<select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct phone FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
<?php
}
?>
</select>
</td></tr></table>
</div>
<div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
var dataname = $('#country').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
function getPhone(val) {
var dataname = $('#phone').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
</script>
// ////////////////////data file data.php rishabh
<?php
$val = $_POST["value_name"];
$colomn = $_POST["colomn_name"];
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
<table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>

Resources