I have Customer Textfield, that contains customer Name. And then, i also have Project Textfield contains project name from customer. I want to make depending dropdown from multi select customer.
For example, user select : btel, celc, from the Customer Textfield, it just appear in Project Text field from btel and celc.
This is my JS:
<script type="text/javascript">
$('.filter_user_customer').select2();
$(document).ready(function(){
$('input[name="daterange"]').daterangepicker({
opens: 'left',
drops: 'up'
}, function(start, end, label) {
console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
});
// key category select box
var $category = $('select#categoryField');
// customer select box
var $customer = $('select#customerField');
// project select box
var $projects = $('select#projectField');
// on change user role, get projects
var $role = $('select#roleField');
// on change user id, get projects
var $userid = $('select#useridField');
// on change combiner
var $combiner = $('combinerField');
$customer.on('change', function () {
// get selected customer name
var customer = $(this).find('option:selected').val();
console.log(customer);
// post data with CSRF token
var data = {
action:'project',
customer: customer,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
// AjaxPOST to get projects
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
projects_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
projects_data += '<option value="'+obj.project_id+'">'+obj.project_id+'</option>';
});
// append all projects in project dropdown
$projects.html(projects_data);
}, 'JSON');
});
// on change user role, get project
$projects.on('change', function () {
// get selected project name
var project = $(this).find('option:selected').val();
// AjaxPOSt wit CSRF
var data = {
action:'role',
project: project,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
role_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
role_data += '<option value="'+obj.user_owner+'">'+obj.user_owner+'</option>';
});
// append all role data in Role dropdown
$role.html(role_data);
}, 'JSON');
});
// on change user ID, get project
$projects.on('change', function () {
// get selected project name
var project = $(this).find('option:selected').val();
// AjaxPOSt wit CSRF
var data = {
action:'userid',
project: project,
"<?=$this->security->get_csrf_token_name()?>" : "<?=$this->security->get_csrf_hash()?>"
};
$.post('<?php echo base_url(); ?>Dashboard/perfomance_monitoring', data, function(json) {
userid_data = '<option value="0">All</option>';
$.each(json, function(index, obj){
userid_data += '<option value="'+obj.user_id+'">'+obj.user_id+'</option>';
});
// append all role data in Role dropdown
$userid.html(userid_data);
}, 'JSON');
});
});
</script>
This is my Controller:
$array_data = array();
// only on Ajax Request
if ($this->input->is_ajax_request()) {
// if request for projects
if ($this->input->post('action') && $this->input->post('action') == 'project') {
// get customer name
$customer = $this->input->post('customer', true);
// get project data by customer name
$array_data = $this->ixt_models->fetch_project(trim($customer), 'project');
// AjaxPOST JSON response
echo json_encode($array_data);die();
}
This is my Model:
public function fetch_project($where_data = null, $type = null)
{
$query = '';
// customer only
if (is_null($type) && is_null($where_data)) {
// desire column from table
$this->db->select('cust_id');
// only unique customer
$this->db->distinct('cust_id');
// mysql table
$query = $this->db->get($this->table_helper);
}
// projects by customer
elseif ($type == 'project' && !is_null($where_data)) {
// desire column from table
$this->db->select('project_id');
// where clause
$this->db->where('cust_id', $where_data);
// mysql table
$query = $this->db->get($this->table_helper);
}
Right now, Project Textfield only show one choice when Customer take more than one selection :
Click here
You can try this code.
JavaScript code:
function onchangeFunctionName(id) {
if (id == '') {
$('#SelectedId').prop('disable', true);
} else {
$('#SelectedId').prop('disable', false);
$.ajax({
url: base_url + '/Url here get value by selected value',
type: "GET",
data: {'id': id},
dataType: 'json',
async: false,
success: function(data) {
$.each(data, function(key, value) {
$('#IdNameWhereShowValue').append('<option ' ' value="' + value.valueId + '">' + value.ValueName + '</option>');
});
},
error: function() {
}
});
}
}
Controller code:
$array_data = $this->ModelName->MethodName(PassIdhere passed by the js code);
echo json_encode(array_data);
Related
I am trying to get all columns and rows to appear after being added to an array in JS and PHP. For some reason, neither the player column nor the status column are filled with content. Any insight into this is appreciated.
This is the code where the array is collected:
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>
And this is the code where the table originates:
var reloadTable = function(data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function(rowNumber, rowData) {
var row = $('<tr>');
//console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
setInterval(function() {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['
id '] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
When you debug, look at the values in your variables to ensure they are what you expect them to be. Your code is treating these variables inconsistently. For example, you're looping over data:
$.each(data ...
Which implies that data is an array. But then you also try to access values on data:
'html': data.eName
I suspect that you actually want to access values on rowData within that iteration:
'html': rowData.eName
(Same error a few more lines down in your code.)
i have problem with my multilevel dependent select lists, i have six select lists dependent on each other and i have write a code to create dynamic lists using jquery. selects named as district, tehsil, project, center, school and user. it is working fine when i choose all options in a sequence, district-> tehsil-> project -> center -> school -> user, and when i change sequence at any level like district -> tehsil -> district( here district is parent of tehsil) after clicking on parent child tehsil not refreshed, and this problem exist in all hierarchy.... this jquery code calls 6 controller and models. those are not include here due to length of question. what should i do ?
this is my jquery code
$('#districts_id,#tehsils_id,#projects_id,#centers_id,#schools_id').on('change', function() {
//alert($("#districts_id option:selected").attr("title"));
//var parameters = {};
var parameters;
var url;
if($('#schools_id').val())
{
$("#users_id").removeAttr('disabled');
//parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
parameters = {"users_schools_id": $('#schools_id').val(), users_gender: $('#gender').val()};
url = "<?php echo base_url();?>/BtaAdministratorUnionMembers/get_teachers_users_by_school_id";
}
else if($('#centers_id').val())
{
$("#schools_id").removeAttr('disabled');
//parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
parameters = {"schools_centers_id": $('#centers_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_schools_by_center_id";
}
else if($('#projects_id').val())
{
$("#centers_id").removeAttr('disabled');
//parameters = JSON.stringify({centers_probject_id:$('#projects_id').val()});
parameters = {"centers_probject_id": $('#projects_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_centers_by_project_id";
}
else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
{
$("#projects_id").removeAttr('disabled');
//parameters = JSON.stringify({projects_tehsil_id:$('#tehsils_id').val()});
parameters = {"projects_tehsil_id": $('#tehsils_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_projects_by_tehsil_id";
//alert(parameters + ' '+ url);
}
else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
{
$("#tehsils_id").removeAttr('disabled');
//$("#tehsils_id").empty();
//parameters = JSON.stringify({tehsils_districts_id:$('#districts_id').val()});
parameters = {"tehsils_districts_id": $('#districts_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_tehsils_by_districts_id";
//alert(parameters + ' '+ url);
}
$.ajax({
type: "GET",
url: url,
data:parameters,
//contentType: "application/json;charset=utf-8",
dataType: 'json',
success: function(data){
//alert(data);
//alert(JSON.stringify(data));
if($('#schools_id').val())
{
//alert(JSON.stringify(data));
$('#users_id').empty();
$('#users_id').append("<option value=''>Select Teacher....</option>");
$.each(data,function(key,value){
$('#users_id').append('<option value="'+value.users_id+'">'+value.users_firstname_users_lastname+'</option>');
});
}
else if($('#centers_id').val())
{
//alert(JSON.stringify(data));
$('#schools_id').empty();
$('#schools_id').append("<option value=''>Select School....</option>");
$.each(data,function(key,value){
$('#schools_id').append('<option value="'+value.schools_id+'">'+value.schools_name+'</option>');
});
}
else if($('#projects_id').val())
{
//alert(JSON.stringify(data));
$('#centers_id').empty();
$('#centers_id').append("<option value=''>Select Center....</option>");
$.each(data,function(key,value){
$('#centers_id').append('<option value="'+value.centers_id+'">'+value.centers_schoolName+'</option>');
});
}
else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
{
//alert(JSON.stringify(data));
$('#projects_id').empty();
$('#projects_id').append("<option value=''>Select Project....</option>");
$.each(data,function(key,value){
$('#projects_id').append('<option value="'+value.projects_id+'">'+value.projects_name+'</option>');
});
}
else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
{
//clearDropDown($('select'), 5);
$('#tehsils_id').empty();
$('#tehsils_id').append("<option value='' title=tehsils_id>Select Tehsils....</option>");
$.each(data,function(key,value){
$('#tehsils_id').append('<option value="'+value.tehsils_id+'" title=tehsils_id>'+value.tehsils_name+'</option>');
});
}
},
error: function(data){
alert(JSON.stringify(data));
//console.log(data);
}
});
});
In each level you have to remove all next options when a top level option is changed and the set the next level again e.g in school level:
$('#schools_id').nextAll("select").each(function(){
$(this).find('option').remove();
})
// Then set again the next level
I used nextAll assuming that selects are siblings. elsewhere you have to use propper selector
With all of your if else statements organized from the most specific to least specific, fiddling with a parent input triggers the event handler but is caught by the else statement for its child.
Use separate event handlers for all six inputs based on the one you are interacting with rather than checking for values alone, and your logic will work morelike you planned.
You'll even be able to more easily handle the case where the user is jumping back a few levels and you should reset/disable a few selects.
I'm developing a ps module which let you classify the product attachment in categories an display them in the front product page.
I'm using a draggable list with the attachment, and when you drop them to the category it turns to an option tag, each category has a select tag where to drop the attachment.
I want to save the attachments and the category where they was dropped, so I thought make an ajax call to bring the data to my module class but I'm new with ajax and cant approach it.
this is what I've made:
the js code (inside the proper .tpl):
<script>
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//var tab = val.split(',');
//for (var i=0; i < tab.length; i++)
//if (tab[i] == $(this).val())
// return false;
//create an array with the next format: 'id_category(1)'-'id_attachment(1)','id_category(2)'-'id_attachment(2)'[....]
//the comma will be the main character that will be splitted
$('#categoryAttachmentArr').val(val + ui.doppable.attr('id') + '-' + ui.draggable.attr('id') +',');
}
});
$('#submitAddProduct').click(function(e){
$.ajax({
type: 'POST',
url: baseDir + 'modules/adjuntos/classes/CategoryAttachment.php',
data: {
ajax: true,
action: \'CategoryArray\',
cat_array: $('#categoryAttachmentArray').val(),
}
dataType: 'json',
success: function(json) {
console.log($('#categoryAttachmentArray').val());
}
});
})
$( ".ui-state-default" ).draggable({
revert: "valid",
});
</script>
And my class:
class CategoryAttachment extends Objectmodel
{
//other functions
public function ajaxProcessCategoryArray()
{
$CategoryAttachmentArr = Tools::getValue('cat_array')
}
}
you can't connect directly to any class. you have to use the controller to do this.
Ajax send data to controller
Controller save data using class
Controller return result to browser (javascript)
Finaly I got the solution, maybe one of you guys will have this problem in the future.
My code in the .tpl:
$( ".ui-state-default" ).draggable();
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
$('#selectAttachment1').append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>')
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//make a serialize() type array
$('#categoryAttachmentArr').val(val + $(this).attr('id') + "=" + ui.draggable.attr('id') +"&");
var value = $('#arrayAttachments').val();
var tab = value.split(',');
for (var i=0; i < tab.length; i++)
if (tab[i] == ui.draggable.attr('id')){
return false;
}
$('#arrayAttachments').val(value+ui.draggable.attr('id')+',');
}
});
$('#submitCategories').click(function(e){
var array = $('#categoryAttachmentArr').val()
$.ajax({
url: '../modules/adjuntos/ajax-call.php',
data: {
action: 'handlearray',
token:new Date().getTime(),
cat: array
},
method: 'POST',
success:function(data){
$('#result').html(data);
}
});
});
the ajax call goes to my ajax-call.php file:
<?php
//load ps config
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
require_once('adjuntos.php');
//adjuntos.php is the name of my module main file
if(Tools::getIsset('token') && Tools::getIsset('action'))
{
$mp = new Adjuntos;
echo $mp->handleArray();
}
The handleArray function in my module main file:(it make a call to my custom class)
public static function handleArray()
{
$html = '';
$array = Tools::getValue('cat');
$arrayExplode = explode("&", $array);
foreach($arrayExplode as $value)
{
$finalArr = explode("=", $value);
if (!CategoryAttachment::postProcess($finalArr))
{
$html .= '<p style="color:red;>Fallo</p>"';
}
}
$html .= '<p style="color:green;>Correcto</p>"';
return $html;
}
The function in my custom class:
public static function postProcess($finalArr)
{
return Db::getInstance()->execute(
'UPDATE ps_attachment SET id_category = '.$finalArr[0].' WHERE id_attachment = '.$finalArr[1]
);
}//end
This way is working like a charm, and make the code more scalable
I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Hi I was able to display a json data(List of conversation result) but I want to display them just like how I display records from database like this:
foreach(res->fetchAll(PDO::FETCH_ASSOC) as result):
$username = $result['username'];
$message = $result['message'];
endforeach;
are there any similar procedure like this but with json_encode() ?
here is my php script
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
This php script are getting its data from my ajax script below
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<p />').html(key + ':' + value));
});
});
}
});
The php and javascript are working fine the JSON are being displayed.. But I'm trying to figure out if there is a way that I can display only the username and the message just how I use the foreach statement that I mentioned above...
I may be misunderstanding, but you should be able to filter what is displayed by adding a condition with an if
$.each(result, function(i, message) {
$.each(message, function(key, value) {
if (key == "username" || key == "message")
container.append($('<p />').html(key + ':' + value));
});
});