I have problem is when i use ajax to send data to php server and get it to display in view, but data can't display in view although it loaded when i check in console. Please help me solved it.
This is my code :
View and script
<div class="col-xs-12" style="display: block; margin-bottom: 10px;">
<h5 class="col-sm-3 col-sm-offset-1 control-label" style="">Vị trí:</h5>
<div id="positionDiv" class="col-sm-3">
<select id="position" tabindex="9" name="recruitment[positions]" value="<?php echo $this->data['recruitment']->positions; ?>" data-none-selected-text class="selectpicker">
<option style="display: none" selected disabled value=""></option>
<?php foreach($this->data['position'] as $key => $value): ?>
<option value="<?php echo $value->positions ?>" <?php if ($this->data["recruitment"]->positions == $value->name): ?>selected<?php endif ?>>
<?php echo $value->name; ?>
</option>
<?php endforeach ?>
</select>
<input id="positionHidden" type="hidden">
</div>
<script>
$(document).ready(function() {
$("#position option").each(function(){
$(this).siblings("[value='"+ this.value+"']").remove();
});
$('#market').on('change', function(event) {
var value = $('#market').val();
$.ajax({
url: window.location.href,
type: 'POST',
data: {
market: value
},
success: function(response){
var indexStart = response.indexOf('id="position"') - 8;
var indexEnd = response.indexOf('positionHidden') - 49;
var str = response.substring(indexStart,indexEnd).replace(/\s\s+/g, ' ');
$('#position').remove();
$('#positionDiv').append(str);
//document.getElementById('positionDiv').innerHTML = str;
console.log($('#positionDiv'));
}
});
});
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.async = true;
});
});
</script>
Controller
class CandidateController extends BaseController {
public function __construct($route, $urlValue) {
parent::__construct($route, $urlValue);
}
public function initData() {
$this->view->setData("resource", ResourceCompany::getAllResource());
$this->view->setData("market", Market::getAllMarket());
}
public function showPosition() {
$market = $_POST['market'];
isset($market) ? $market : null;
$this->view->setData("position", Recruitment::getPositionByMarket($market));
}
public function showTitle() {
isset($market) ? $market : null;
isset($position) ? $position : null;
$this->view->setData("title", Recruitment::getTitleByMarketPosition($market, $position));
}
public function register() {
$this->initData();
if (isset($_POST['market'])) {
$this->showPosition();
}
}
$this->view->output("menu");
}
Everything alright, data send and get is okay but it can't display in view although i can get it from console.log.
mybe you have special characters in your content.
you most replace this characters before send in php code and reverse after get in javascript
"&" = & amp;
"\"" = & quot;
"'" = & apos;
"<" = & lt;
">" = & gt;
remove space after & plase
Related
I have tried the following but what i need just to populate two dependent drop down (penality_type based on vehicle_type) list:
Is there some one to show me how to implement here please:
This is my Controller:
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$data['penality_type'] = $this->vehicle_type_model->getAllPenalityType();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
This is vehicle_type_model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class vehicle_type_model extends CI_Model {
/*
* Get All Vehicle types
*/
public function getAllVtype()
{
$result = $this->db->get('vehicle_type');
return $result->result_array();
}
public function getAllPenalityType()
{
$result = $this->db->get('penality_type');
return $result->result_array();
}
}
This is my View:
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type_id" class="form-control vehicle_type_id">
<option value="">Select Vehicle type</option>
</select>
</div>
<div class="form-group">
<label for="penality_type_id">penality type</label>
<select name="penality_type_id" class="form-control penality_type_id">
<option value="">Select penality type</option>
</select>
</div>
What you are doing is incorrect. I assume that your penalty type is dependent on vehicle type, so you should pass vehicle_type id through ajax to the controller, then to your database and load them into the penalty type drop-down.
Please refer below code
Your index function will have just this,
public function index()
{
$data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
$this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}
Your view
<div class="form-group">
<label for="vehicle_type_id">Vehicle Type</label>
<select name="vehicle_type" class="form-control vehicle_type_id" id = "vehicle_type">
<option value="">Select Vehicle type</option>
<?php foreach($vehicle_type as $row) { ?>
<option value="<?php echo $row->vehicle_type_id ?>"><?php echo $row->vehicle_type_name; ?></option>
<?php } ?>
</select>
</div>
AJAX Code
var base_url = "<?php echo base_url; ?>";
$("#vehicle_type").change(function () {
if ($('#vehicle_type').val() != "") {
$.ajax({
url: base_url + "your_controller/get_penality_by_id",
type: 'POST',
cache: false,
data: {
'vehicle_type_id': $('#vehicle_type').val()
},
success: function (data) {
if($data){
$("#penality_type").html(data);
}
}
});
}
});
Controller
public function get_penality_by_id(){
$vehicle_type_id = $this->input->post('vehicle_type_id');
$data = array('vehicle_type_id' => $vehicle_type_id);
$result = $this->your_model_name->get_penality($data);
if($result){
$option = "<option value=''>--Select an Option--</option>";
foreach ($result as $row){
$option .= "<option value='".$row->penality_id."'>".$row->penality_name."</option>";
}
echo $option;
}else{
echo $option = "<option value=''>--Select an Option--</option>";
}
}
Model
public function get_penality($data){
$this->db->select('*');
$this->db->from('table-name');
$this->db->where($data);
$result_set = $this->db->get();
if($result_set->num_rows() > 0){
return $result_set->result();
}
else {
return FALSE;
}
}
Please note that your vehicle type drop-down option will have the vehicle_type id, which can be used for fetching your dependent penalty. Hope this can help you.
I am creating dependable select option in codeigniter. To populate first option was easy but i am bit troubling in displaying the second option and third option. Need help on this
My database contain:
In head table:
h_id, head fields,
subhead table
h_id, sh_id, subhead fields and
points table
sh_id, points_name fields
controller
class Mobile extends App_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper(array('url','language','form'));
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
$this->lang->load('auth');
$this->load->model('mobiles_model');
}
function index()
{
if (!$this->data['logged_in'])
{
redirect('auth/login','refresh');
}
$rows = $this->mobiles_model->get_users_devices();
if ($rows)
{
$this->data['devices_list'] = $rows;
}
$this->_render_page('trackall', $this->data);
}
function _render_page($view, $data=null, $render=false)
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $render);
if (!$render) return $view_html;
}
}
modal
public function get_users_devices()
{
$this->db->select('A.h_id as id,A.head');
$this->db->from($this->table_head.' as A');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
return FALSE;
}
view
<select id="head" name="head" class="form-control input-sm" onchange = "calljavascriptfunction();">
<option value="default">--Select--</option>
<?php if(isset($devices_list))
foreach ($devices_list as $value) { ?>
<option value="<?php echo $value['h_id'] ?>"><?php echo $value['head'] ?></option>
<?php } ?>
</select>
<select id="subhead" name="subhead" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
<select id="points" name="points" class="form-control input-sm">
<option value="default">--Select--</option>
</select>
I have to populate the other depending on what i select. i tried several methods but none of them worked.
Thanks for help i am really stuck in this.
Suppose your you had following views loaded in HTML and you need to fetch value depending on first dropdown #head.
view code :
<select id="head">
<option id="1"> Mobile </option>
<option id="2"> Tabs </option>
<option id="3"> Laptops </option>
</select>
<select id="subhead">
</select>
jquery ajax
$("#head").change(function(){
var post_url = '<?php echo base_url() ?>mobile/getByDeviceId'
$.ajax({
type: "POST",
url: post_url,
data : { "hid" : $(this).val() },
success: function(response){
$.each(response, function(value, key) {
$("#subhead").append("<option id="+value.modelId+">"+value.modelName+"</option>");
})
}
});
});
controller function :
function getByDeviceId(){
$hid = $this->input->post("hid");
$modelList = $this->mobile_model->getByDeviceId($hid);
echo(json_encode($modelList));
}
model function :
function getByDeviceId($hid){
$this->db->select("modelId, modelName");
$this->db->from("models");
$this->db->where("hid", $hid);
$query = $this->db->get();
return $query->result();
}
Use jquery ajax() to do this, as ajax() do not disturb the current state of page and get the data from server and you can append it to the dropdown.
ajax() syntax:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
var1 :val1,
var2 :val2
},
success: function(response){ // response from process
// do your stuff here
}
});
here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.
I can't get the text in form_dropdown it always return the option value. Please help.
view
<?php echo form_open_multipart('upload/do_upload');?>
<?php
$cont ='';
$dept='';
foreach($level->result() as $row) {
$cont = $row->userlevel;
$dept = $row->department;
}
if(strtoupper($cont)=="USER") {
echo "<strong>".$dept." </strong>";
}
else {
echo form_dropdown('department_name', $dept_name,'','id="department_name"');
}
?>
<br/><br/>
<div class="btn-group">
<span id="status2"><?php echo form_dropdown('document_name', $document_name, '', 'id="document_name"'); ?></span>
</div>
<br/><br/>
<label for="file">Select File To Upload:</label>
<input type="file" name="userfile" multiple class="btn btn-file"/>
</br></br>
<input type="submit" value="Upload File" class="btn btn-primary"/>
<?php echo form_close(); ?>
<script>
window.onload = function() {
var form_data = {
dept_name: "<?php echo $dept; ?>",
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
};
$("#department_name").change(function() {
var form_data = {
dept_name: $("#department_name option:selected").text(),
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
});
</script>
controller
$upload_data = $this->upload->data();
$data['thumbnail_name'] = $upload_data['raw_name']. '_thumb' .$upload_data['file_ext'];
$file_array = array(
'image' => $data['thumbnail_name'],
'image_name' => $upload_data['file_name'],
//'description' => "",
'date_created' => date('Y-m-d H:i:s', now()),
'date_modified' => date('Y-m-d H:i:s', now()),
'author' => $this->session->userdata('username'),
'size' => $upload_data['file_size'],
'type' => $upload_data['image_type'],
'width' => $upload_data['image_width'],
'height' => $upload_data['image_height'],
'document_name' => $this->input->post("document_name"),
'department' => $this->input->post("department_name"),
//'notes' => "",
);
when I try this...
print_r($this->input->post("document_name"));
print_r($this->input->post("department_name"));
it shows 1 and 1...
what I want is the text not the id or value of options.
Example: I selected the IT Department and Folder 1, it will display/record IT Department and Folder 1 to database.
Check this: http://jsfiddle.net/Lev0sjjx/2/
Note: The jquery code is just for demonstration purposes
HTML
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Javascript / jQuery
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
$(function() {
$('#test').change(function() {
var text = getSelectedText('test');
alert(text);
});
});
Exchange array values and keys:
$dept_name = array_flip($dept_name);
form_dropdown('department_name', $dept_name,'','id="department_name"');
Same for $document_name.
This switches from <option value="id">name</option> to <option value="name">id</option>.
If you need <option value="name">name</option>, rebuild the array to get a name 2 name relationship.
$dept_names2 = array();
foreach($dept_name as $item_id => $item_name)
{
$dept_names2[$item_name] = $item_name; // name as key and value
}
form_dropdown('department_name', $dept_names2,'','id="department_name"');
An array with structure "name=>name" will work with your ajax requests, too - because you are using $("#department_name option:selected").text(). so you are already working with the names, not the ids. no adjustment needed.