My Codeigniter site has side panel and when i click or select any options in side panel appropriate content will appear to the main panel.
Home page URL is http://localhost/main/userinfo/allusers
When i click female button URL is http://localhost/main/userinfo/female
i have following output when i made the Ajax request. Where i did the mistake?
Controller(main.php)
class Main extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('userinfo_model');
}
public function index() {}
public function userinfo($gender) {
$this->load->view('home/inc/header_view');
$usermain_data['user_info'] = $this->userinfo_model->get_data($gender);
$this->load->view('home/main_view', $usermain_data);
}
Model(userinfo_model.php)
class Userinfo_model extends CI_Model {
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get_data($gender) {
$this->db->select('*');
if($gender == 'female'){
$this->db->where('gender', 0);
}
elseif($gender == 'male'){
$this->db->where('gender', 1);
}
elseif($gender == 'allusers'){
$gNames = array(0, 1);
$this->db->where_in('gender', $gNames);
}
else {
redirect(base_url() . 'main/userinfo/allusers');
}
$query = $this->db->get('tble_userinfo');
//return $query->result();
echo(json_encode($query->result()));
}}
View(main_view.php)
<div class="container">
<div class="row">
<div class="col-md-3 side_menu">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default gender-label" id="lbl-female" onclick="displayfemale()">
<input type="radio" name="options" id="option1" autocomplete="off">
<span>Female</span>
</label>
<label class="btn btn-default gender-label" id="lbl-male" onclick="displaymale()">
<input type="radio" name="options" id="option2" autocomplete="off">
<span>Male</span>
</label>
</div> <br> <br>
<label class="label nav-label">Age</label>
<select class="btn nav-age-select" id="ageSelect1" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21" selected="selected">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
<label class="label nav-label label-to">To</label>
<select class="btn nav-age-select" id="ageSelect2" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25" selected="selected">25</option>
</select>
</div>
<div class="col-md-8 main-body">
<div id="userdata">
<?php
//foreach ($user_info as $info) {
//confuse of adding date here with ajax
//echo $info->content . '<br />' . $info->added_date .'<br />';
//}
?>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var ajaxUrl = '<?php echo base_url(); ?>' + 'main/userinfo';
var gender = 'allusers'; // defual 1 for female and male both together
getAjax(ajaxUrl, gender);
$("#lbl-female").click(function () {
gender = 'female';
getAjax(ajaxUrl, gender);
});
$("#lbl-male").click(function () {
gender = 'male';
getAjax(ajaxUrl, gender);
});
});
function getAjax(ajaxUrl, gender){
ajaxUrl = ajaxUrl + '/' + gender;
$.ajax({
url: ajaxUrl,
dataType: "JSON",
type: "POST",
success: function (retdata) {
$("#userdata").html('');
if(retdata.hasOwnProperty("error")){
$("#userdata").html('<div">' + retdata.msg + '</div>');
}
else{
$.each(retdata, function(i){
$("#userdata").append(retdata[i].content + '<br>');
});
}
}
});
}
This answer will have main load both genders initially. Rather than use several gender specific URLs the gender buttons will return the html of the selected gender and dynamically change the html of the page.
main_view.php (with Javascript included)
<div class="container">
<div class="row">
<div class="col-md-3 side_menu">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default gender-label" id="lbl-female">
<input type="radio" name="options" id="option1" autocomplete="off">
<span>Female</span>
</label>
<label class="btn btn-default gender-label" id="lbl-male">
<input type="radio" name="options" id="option2" autocomplete="off">
<span>Male</span>
</label>
</div> <br> <br>
<label class="label nav-label">Age</label>
<select class="btn nav-age-select" id="ageSelect1" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21" selected="selected">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
<label class="label nav-label label-to">To</label>
<select class="btn nav-age-select" id="ageSelect2" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25" selected="selected">25</option>
</select>
</div>
<div class="col-md-8 main-body">
<div id="userdata">
<?php
foreach($user_info as $info)
{
echo $info->content.'<br />'.$info->added_date.'<br />';
}
?>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
var ajaxUrl = '<?php echo base_url(); ?>' + 'main/userinfo';
$("#lbl-female").click(function () {
getAjax(ajaxUrl, 'female');
});
$("#lbl-male").click(function () {
getAjax(ajaxUrl, 'male');
});
});
function getAjax(URL, gender) {
$.ajax({
url: URL,
data: {gender: gender},
dataType: "html",
type: "POST",
success: function (retdata) {
$("#userdata").html(retdata);
}
});
}
</script>
Note that in the $.ajax options with the line
data: {gender: gender},
we are "posting" data to the controller which will be retrieved by using $this->input->post("gender"); in the AJAX response function.
Models should not do anything but return data for a controller to use. It is the controller's job to determine what happens based on the data returned. So the redirect() call has been removed.
Userinfo_model.php
class Userinfo_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
// Note the default value for argument $gender.
// This means you do not have to pass an argument.
// If you don't pass one, then !empty($gender) === FALSE
function get_data($gender = NULL)
{
$this->db->select('*');
//select based on gender.
//If no $gender then a "where" clause is not needed and both genders are selected
if(!empty($gender))
//an argument was provided
{
if($gender == 'female')
{
$this->db->where('gender', 0);
}
else
{
$this->db->where('gender', 1);
}
}
$query = $this->db->get('tble_userinfo');
return $query->result();
}
}
Finally, we get to the controller. index() will display both genders by calling get_data() without passing an argument to the model. After that the AJAX responder userinfo() will return html of the desired gender to the ajax success function. The success function will replace the existing html with the new html echoed from userinfo().
class Main extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('userinfo_model');
}
public function index()
{
$usermain_data['user_info'] = $this->userinfo_model->get_data();
$this->load
->view('home/inc/header_view')
->view('home/main_view', $usermain_data);
}
//Only used to respond to an AJAX request
public function userinfo()
{
$gender = $this->input->post('gender');
if(empty($gender))
{
$out = "No Users Found";
}
else
{
$user_info = $this->userinfo_model->get_data($gender);
$out = "";
foreach($user_info as $info)
{
$out .= $info->content.'<br />'.$info->added_date.'<br />';
}
}
echo $out;
}
}
This seems reasonably secure so far. The only user input is the gender value. (Never trust user input) Should someone try to pass a value other than the string "female" the database will return only the males info. No user input is presented directly to the database so I don't see any vulnerabilities.
Related
I want to pass a dropdown value to a JsonList and save it to the DB. Json list is first sent to the controller file and then it'll call the relevant Model and class. It works when the input type is a text. But doesn't work when it's a dropdown. Below are my codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="Psychlarity">
<!--<link rel="shortcut icon" href="../images/favicon.png" type="image/png">-->
<title>Psychlarity</title>
</head>
<body>
<form method="POST" id="add_article_station" data-toggle="validator">
<div class="panel-heading">
<h4 class="panel-title"><i aria-hidden="true" class=""></i>Add New Question </h4>
<p>Use this form to add a new question to the system</p>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-md-4">
<label>Age Category <span class="text-danger"></span></label>
<select name="age" id="age" class="select-css" >
<option disabled="disabled" selected="selected" >Select Age Category</option>
<option value="t">Teen</option>
<option value="a">Adult</option>
<option value="e">Elder</option>
<option value="">Any</option>
</select>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Relationship Status Category <span class="text-danger"></span></label>
<select name="RS" id="RS" class="select-css" >
<option disabled="disabled" selected="selected">Select Relationship Status Category</option>
<option value="m">Married</option>
<option value="n">Single</option>
<option value="">Any</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Employement Status Category <span class="text-danger"></span></label>
<select name="ES" id="ES" class="select-css" >
<option disabled="disabled" selected="selected" >Select Employement Status Category</option>
<option value="e">Employed</option>
<option value="s">Student</option>
<option value="u">Unemployed</option>
<option value="">Any</option>
</select>
</div>
</div> <br> <br>
<div class="row pull-right">
<div class="col-md-12">
<button class="btn btn-success btn-quirk btn-wide mr5">Submit</button>
<button class="btn btn-quirk btn-wide btn-default" type="reset">Reset</button>
</div>
</div>
</div></div></div></div></div></div></form></div></section>
<script>
$("#add_article_station").validator().on('submit', function (event) {
if (!event.isDefaultPrevented()) {
var formData = new FormData($('#add_article_station')[0]);
console.log(formData);
$.ajax({
url: "../../Controller/AddquestionController.php",
type: 'POST',
data: formData,
async: false,
success: function (data) {
try {
var json = JSON.parse(data)
if (json.code == 200) {
window.location = "?msg=suc";
// alert(json.message);
} else {
window.location = "?msg=err";
}
} catch (e) {
window.location = "?msg=err";
}
}, error: function (data) {
toastr.error("Error In Saving");
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
$(document).ready(function () {
'use strict';
function getParam(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
$(function () {
if (getParam("msg") == "suc") {
toastr.success("Sucssfully saved.");
} else if (getParam("msg") == "err") {
toastr.success("Question saved.");
}
});
</script>
<?php include '../includes/notificationJS.php'; ?>
</body>
</html>
The below is my Model where the DB query is.
public static function Addquestion($article, $logedUser) {
if (TokenValidationModelClass::TokenValidate($logedUser)) {
$dbh = dbconnect::Connection();
$addquestionStmtStmt = $dbh->prepare("INSERT INTO questions
(age_cat,employment_status,relationship_status)
VALUES
(:age_cat,:employment_status,:relationship_status); ");
$addquestionStmtStmt->bindParam(':age_cat', $article->age);
$addquestionStmtStmt->bindParam(':employment_status', $article->es);
$addquestionStmtStmt->bindParam(':relationship_status', $article->rs);
if ($addquestionStmtStmt->execute()) {
return HttpStatusMessageRest::getHttpStatusMessage(200);
}
}
return HttpStatusMessageRest::getHttpStatusMessage(401);
}
If anyone needs, below is the controller file of it.
<?php
include '../Model/session_include.php';
require_once("../Model/articleModelClass.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = (object) $_POST;
// print_r($data);
if (!empty($data)) {
if (!empty($data->token)) {
echo articleModelClass::Addquestion($data, $data->token);
} else {
$token = (object) $_SESSION;
// print_r($token);
echo articleModelClass::Addquestion($data, $token);
}
} else {
$error["error"] = "Empty field.";
echo json_encode($error);
}
}
?>
I'm using form validation jquery. And form input like this
<form id="form-valid">
<select id="country" name="country" class="input-group form-control input-sm">
<option value="Asia">Asia</option>
<option value="America">America</option>
<option value="Eropa">Eropa</option>
<option value="Africa">Africa</option>
<option value="Australia">Australia</option>
</select>
<input type="text" id="codetax" name="codetax"><input>
<select id="status" name="status" class="input-group form-control input-sm">
<option value="small">samll island</option>
<option value="big">big island</option>
<option value="medium">medium island</option>
</select>
<button class="btn btn-default btn-primary btn-sm btn-form-filter form-control" data-target="tmppo" id="btnsave" type="button">Save</button>
</form>
But my problem is, i need to check if country are Asia, taxcode and status must filled. But if country not Asia, taxcode and status can be empty. How do i did that when i'm using submit button?? I'm still new about jquery form validate. Pls help me.
Update ok it's works now, i do this on my from validate using depends
$('#form').validate({
errorElement: 'span',
errorClass: 'help-block',
rules: {
country: {
required: true
},
taxcode: {
required: {
depends: function(element) {
if ($('#country').val() == 'Asia') {
return true;
} else {
return false;
}
}
}
},
},
messages: {
codetax : "Pleasa instert taxcode
},
});
And on code html i have to use "name" to get rules. For all tq for helping me :)
I think you want to use the built-in method supplied by the validate library via .addMethod() found on the documentation site. I modified your form to better conform.
<script>
$(document).ready(function() {
// Add the method here, you can modify the code inside as need be
$.validator.addMethod("country", function(value, element) {
if(value == 'Asia') {
var getCodeTax = $('input[name=codetax]').val();
if(getCodeTax === '') {
return false;
}
}
return true;
}, 'You must select tax code');
$('form').validate({
rules: {
status:"required",
// This applies the country method above to the country dropdown
country: "country"
},
messages: {
}
});
});
</script>
<form id="form-valid" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="country" id="country" class="input-group form-control input-sm">
<option value="">Select</option>
<option value="Asia">Asia</option>
<option value="America">America</option>
<option value="Eropa">Eropa</option>
<option value="Africa">Africa</option>
<option value="Australia">Australia</option>
</select>
<input type="text" id="codetax" name="codetax" />
<select id="status" name="status" class="input-group form-control input-sm">
<option value="small">samll island</option>
<option value="big">big island</option>
<option value="medium">medium island</option>
</select>
<input class="btn btn-default btn-primary btn-sm btn-form-filter form-control" value="save" data-target="tmppo" id="btnsave" type="submit">
</form>
You create a function to check what type of country selected on button click event
$( "btnsave" ).click(function() {
var country = $("country").val();
if (country == 'Asia')
{
//show required message here.
}
}
Change type of the button to submit.
$(document).on('submit', '#form-valid' function(e){
var country = $("#country").val();
if(country == 'Asia'){
if($('#codetax').val()=="" || $('#status').val()==""){
e.preventDefault();
//now form won't submit. Still need to add error messages.
}
}
});
If you don't want to change the type of button to submit then :
$(document).on('click', '#btnsave' function(e){
var country = $("#country").val();
if(country == 'Asia'){
if($('#codetax').val()!="" && $('#status').val()!=""){
$('#form-valid').submit();
}
else{
//add your error messages
}
}
});
My Codeigniter site has side panel and when i click or select any options in side panel appropriate content will appear to the main panel.
Home page URL is http://localhost/main/userinfo
When i click female URL is http://localhost/main/userinfo/female
I made an ajax request to get data from the database. I think i have done a mistake. don't know where it is.
Controller(main.php)
class Main extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('userinfo_model');
}
public function index() {}
public function userinfo($gender) {
$this->load->view('home/inc/header_view');
$usermain_data['user_info'] = $this->userinfo_model->get_data($gender);
$this->load->view('home/main_view', $usermain_data);
}
Model(userinfo_model.php)
class Userinfo_model extends CI_Model {
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get_data($gender) {
$this->db->select('*');
if($gender == 'female'){
$this->db->where('gender', 0);
}
elseif($gender == 'male'){
$this->db->where('gender', 1);
}
elseif($gender == 'allusers'){
$gNames = array(0, 1);
$this->db->where_in('gender', $gNames);
}
else {
redirect(base_url() . 'main/userinfo/allusers');
}
$query = $this->db->get('tble_proposal');
return $query->result();
}}
View(main_view.php)
<div class="container">
<div class="row">
<div class="col-md-3 side_menu">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default gender-label" id="lbl-female" onclick="displayfemale()">
<input type="radio" name="options" id="option1" autocomplete="off">
<span>Female</span>
</label>
<label class="btn btn-default gender-label" id="lbl-male" onclick="displaymale()">
<input type="radio" name="options" id="option2" autocomplete="off">
<span>Male</span>
</label>
</div> <br> <br>
<label class="label nav-label">Age</label>
<select class="btn nav-age-select" id="ageSelect1" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21" selected="selected">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
<label class="label nav-label label-to">To</label>
<select class="btn nav-age-select" id="ageSelect2" autocomplete="off">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25" selected="selected">25</option>
</select>
</div>
<div class="col-md-8 main-body">
<div id="userdata">
<?php
foreach ($user_info as $info) {
//confuse of adding date here with ajax
//echo $info->content . '<br />' . $info->added_date .'<br />';
}
?>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var ajaxUrl = '<?php echo base_url(); ?>' + 'main/userinfo';
var gender = 'allusers'; // defual 1 for female and male both together
getAjax(ajaxUrl, gender);
$("#lbl-female").click(function () {
gender = 'female';
getAjax(ajaxUrl, gender);
});
$("#lbl-male").click(function () {
gender = 'male';
getAjax(ajaxUrl, gender);
});
});
function getAjax(ajaxUrl, gender){
ajaxUrl = ajaxUrl + '/' + gender;
$.ajax({
url: ajaxUrl,
dataType: "JSON",
type: "POST",
success: function (retdata) {
//append data, Then do i have to change the data select part from the database
}
});
}
You have 2 choices:
Can make AJAX call to different function in the controller that
return a JSON object, the process it with javascript code.
Or you can return a partial view with the just the html you need and place
in userdata container.
I have a simple jquery function that reflects the selected value of a dropdown to textbox but the problem is that the console says that my function was undefined. I put the function inside the onchange event of the dropdown. Please note that all of my jquery functions was on the bottom of the page..
and here is the dropdown:
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<?php
foreach($operation as $val)
{
?>
<option value="<?php echo $val['OperationName'];?>"><?php echo $val['OperationName'];?></option>
<?php
}
?>
</select>
<span class="text-danger"><?php echo form_error('operation');?></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
this is the operation array model
function getDeliveryDays($str)
{
$this->db->select('DeliveryDays');
$this->db->from('operation');
$this->db->where('OperationName',$str);
return $this->db->get()->result();
}
this is the controller:
public function getDays()
{
$id = $this->input->post('q');
$data['days'] = $this->wip_model->getDeliveryDays($id);
echo json_encode($data);
}
I took the working in my other project and use it in my current project but still the same result and when I inspect it in the dev tools, the said script is missing in view source but it's present in IDE:
this is the code:
function showDeliveryDay(operation)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('wip/getDays/');?>",
data: {q:operation},
success: function(data){
console.log(data);
},
});
}
Thanks in advance....
Does you put the function inside domready? If so, remove that and placed it outside like so :
<script>
function showDays() {
var x = document.getElementById("operationName").value;
document.getElementById("deldays").innerHTML = x;
}
// domready here
$(function(){...}); // or $(document).ready(function(){...});
</script>
Make sure you are including your jquery in your code. try this:
jQuery( document ).ready(function() {
jQuery( "#operationName" ).change(function() {
var pVal = jQuery("#operationName").val();
jQuery("#deldays").val(pVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<span class="text-danger"></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
</div>
You can refer this code
Html
<div class="form-group">
<label class="control-label">Operation</label>
<select class="form-control" id="operationName" name="operationName">
<option value="">-SELECT-</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<span class="text-danger"></span>
<input type="text" class="form-control" id="deldays" name="deldays"
value="" />
Js code
jQuery( document ).ready(function() {
jQuery('#operationName').on('change', function(){
var p=jQuery(this).val();
jQuery("#deldays").val(p);
});
});
You can view demo here
I'm trying to figure out how to have jQuery show/hide a dynamically generated textbox based on a pulldown menu selection. My JS skills are extremely limited. I have the following created in a while loop, depending on the number of people:
<select name="location[<?=$pid?>]" id="location[<?=$pid?>]">
<option value="<?=$loc_id?>" selected><?=$loc_name?> </option>
<option value="Other">Other</option>
<option value="Other">--------</option>
<? $query_loc = mysqli_query($link, "SELECT * FROM locations WHERE loc_app = 'Y' ORDER BY loc_name ASC");
while($fetch_loc = mysqli_fetch_array($query_loc)){
$loc_id = $fetch_loc['loc_id'];
$loc_name = $fetch_loc['loc_name'];
?>
<option value="<?=$loc_id?>"><?=$loc_name?></option>
<?
} ?>
</select>
<input name="location_other[<?=$pid?>]" type="text" id="location_other[<?=$pid?>]" style="display:none" />
jQuery function:
<script type='text/javascript'>
$(window).load(function(){
$('#location').change(function () {
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
});
});
</script>
I need to keep the id of the and the serialized with the $pid variable for later processing. Is there another way to call the jquery function on these?
The HTML output looks like this:
<select name="location[287]" id="location[287]">
<option value="1" selected>A</option>
<option value="Other">Other</option>
<option value="Other">--------</option>
<option value="12">B</option>
<option value="12">C</option>
</select>
<input name="location_other[287]" type="text" id="location_other[287]" style="display:none" />
Try
$(window).load(function(){
$('#location').change(function () {
$('input[id^=location_other]').hide();
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other' + $(this).val()).hide();
}
});
});
Try this
<select name="location[287]" id="location[287]">
<option value="Other">Other</option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<input name="location_other[287]" type="text" id="location_other" style="display:none" />
<script type='text/javascript'>
$(window).load(function() {
if ($('select[id^="location"]').val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
$('select[id^="location"]').change(function() {
if ($(this).val() == "Other") {
$('#location_other').show();
} else {
$('#location_other').hide();
}
});
});
</script>