Magicsuggest setValue() changes when move to other field - php

On selectionchange I am setting the new value but when it focus out the setValue change.
here is my code :
var ms=$('#mydiv').magicSuggest({
useCommaKey: true,
hideTrigger: true,
placeholder: 'Search here',
allowDuplicates: false,
data: '/getData.php',
ajaxConfig: {
xhrFields: {
withCredentials: true,
}
},
valueField: 'name',
renderer: function(data){
return data.full_name;
},
resultAsString: true
});
$(ms).on('selectionchange', function(e, cb){
var response = cb.getValue();
var respone_ary = response.toString().split(',');
if(respone_ary.length > 1){
this.removeFromSelection(cb.getSelection());
this.setValue(respone_ary);
}
});
For Example : In response I am getting "xyz,abc" then I want to set it as two different bobble like this "xyz" "abc" .
It's get set but when I click on other filed it get change to "xyz"
Thanks in advance

Related

Why echo function print data in console?

I'm creating page in PHP but when I use AJAX to send data, echo function start to printing data in console instead in DOM elements.
I want to add Quagga barcode reader to my page. Quagga is write in JS but my page is in php. So I have to use Ajax to send barcode result to my php code. And there is a problem. After sending data (POST) and using echo to display that on the screen, every data that echo should display are showing up in console. Not only data I send but whole page html code too. Even header('Location: ') doesn't work correctly. Because I'm sending readed code to barcodereaded.php where I put POST data inside SESSION var, and I try to echo that on the screen in different file barcoderesult.php but everytime data is printed in console log in barcode.php (which code is below). On every other subpage php echo and header functions works fine, only this one case causing troubles.
<div id="scanner-container"></div>
<input type="button" id="btn" value="Start/Stop" />
<script src="js/quagga.min.js"></script>
<script>
var _scannerIsRunning = false;
function startScanner() {
var barcode = {};
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
numOfWorkers: navigator.hardwareConcurrency,
target: document.querySelector('#scanner-container'),
constraints: {
size: 1920,
width: 200,
height: 480,
facingMode: "environment"
},
},
config: {
frequency: 5,
},
locator: {
patchSize: "x-large",
},
decoder: {
readers: [
"code_128_reader",
"ean_reader",
"ean_8_reader",
"code_39_reader",
"code_39_vin_reader",
"codabar_reader",
"upc_reader",
"upc_e_reader",
"i2of5_reader"
],
debug: {
showCanvas: true,
showPatches: true,
showFoundPatches: true,
showSkeleton: true,
showLabels: true,
showPatchLabels: true,
showRemainingPatchLabels: true,
boxFromPatches: {
showTransformed: true,
showTransformedBox: true,
showBB: true
}
}
},
}, function (err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
// Set flag to is running
_scannerIsRunning = true;
});
Quagga.onProcessed(function (result) {
var drawingCtx = Quagga.canvas.ctx.overlay,
drawingCanvas = Quagga.canvas.dom.overlay;
if (result) {
if (result.boxes) {
drawingCtx.clearRect(0, 0, parseInt(drawingCanvas.getAttribute("width")), parseInt(drawingCanvas.getAttribute("height")));
result.boxes.filter(function (box) {
return box !== result.box;
}).forEach(function (box) {
Quagga.ImageDebug.drawPath(box, { x: 0, y: 1 }, drawingCtx, { color: "green", lineWidth: 2 });
});
}
if (result.box) {
Quagga.ImageDebug.drawPath(result.box, { x: 0, y: 1 }, drawingCtx, { color: "#00F", lineWidth: 2 });
}
if (result.codeResult && result.codeResult.code) {
Quagga.ImageDebug.drawPath(result.line, { x: 'x', y: 'y' }, drawingCtx, { color: 'red', lineWidth: 3 });
}
}
});
Quagga.onDetected(function (result) {
Quagga.stop();
barcode.code = result.codeResult.code;
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
});
}
// Start/stop scanner
document.getElementById("btn").addEventListener("click", function () {
if (_scannerIsRunning) {
Quagga.stop();
_scannerIsRunning = false;
} else {
startScanner();
}
}, false);
</script>
I just want to send readed barcode to other file to convert it into data I want to add to database (quantity of elements on the pallet, production date, etc.)
Look at this part of your code :
$.ajax({
url: "barcodereaded.php",
method: "POST",
data: barcode,
success: function(res){
console.log(res);
}
});
The success method tells what to do with the result of your ajax code.
And here you specifically tell to log the response (res) to the console.
Instead you can use the content of res to append it to your dom via your preferred Javascript solution (vanilla, jQuery,...).
With jQuery you could (if the result from your php code is some text):
$('#my-return-container').text(res)

ExtJS combobox set initial value dynamically from remote store on page load via PHP

My current issue relates to showing an initial value in an ExtJS combobox relating to an employee's department in an employee detail page.
The page retrieves the employee information via PHP, so all the references to the employee are done through PHP echo (the site uses CodeIgniter, which may confuse some; it just simplifies some of the input but works in the same way as normal PHP), i.e.
var formPanel = Ext.create('Ext.form.Panel', {
title: 'User Details',
width: 300,
renderTo: Ext.get('details'),
store: userStore,
defaultType: 'textfield',
items:
[
{
fieldLabel:'User Name',
name: 'UserName',
allowBlank: false,
value: '<?php echo $Employee->UserName; ?>'
},
//More details in similar format etc.
]
});
There is a section for the departments, to be handled through a combobox, to list all departments; there is nothing fancy (I believe), it just lists all the departments:
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
fields: [
{name:'Id', type: 'int'},
{name:'Name', type: 'string'}
]
});
var deptStore = Ext.create('Ext.data.Store', {
model:'DeptModel',
autoload: true,
proxy: {
// load using HTTP
type: 'ajax',
url: '<?= $site_url ?>Settings/JSON/Departments',
reader: {
type: 'json',
model: 'DeptModel'
}
}
});
The formPanel above then references the deptModel/deptStore in a comboBox:
{
fieldLabel:'Department',
xtype:'combo',
name:'Department',
forceSelection: true,
typeAhead: true,
allowBlank: false,
emptyText: 'Choose a Department',
store: deptStore,
displayField: 'Name',
valueField: 'Id'
}
The above combobox renders correctly and provides all the departments. Attempts to initialise the combobox with a value, however, have not worked, ranging from no change in the combobox to creating errors that stop the page rendering. I have looked at the following:
value: 5 // or any integer
value: '5' // or any string
value: <?php echo $Employee->DepartmentId ?> // or any PHP reference like those that work for the textfields e.g. the User Name above - DepartmentId has been checked to be an integer
value: '<?php echo $Employee->DepartmentId ?>' // stringifying the PHP reference
value: 'Accounts'
I have also looked at the numerous posts relating to loading stores after rendering, setting values on store loading, setting values on render, setting values before the formPanel code; quite frankly, none have worked, and most refer to setting the value to the first in the list which doesn't treat my particular issue.
Ideally, I want to simply state
value: <?php echo $Employee->DepartmentId ?>
to have the combobox display the relevant department (i.e. "Accounts") when the employee's details are displayed in the form on page load.
Where am I going wrong? Why does value: {value} not do anything in practice? Can anyone provide a simple explanation as to the correct form of inserting a combobox into a formPanel that allows for the initial value in said combobox to be picked on page load, if the current implementation is somehow incorrect?
JsonStore:
var articleMain = new Ext.data.JsonStore({
model: 'ArticleMainGroup',
autoLoad: true,
proxy: {
type: 'ajax',
url: '<?php echo base_url() ?>dashboard/create',
extraParams: {
type: 'article_group_main'
},
reader: {
type: 'json',
root: 'articleMainGroup',
idProperty: 'ART_GROUP_ID'
}
}
});
Data Model :
Ext.define('ArticleMainGroup', {
extend: 'Ext.data.Model',
fields: [
{name: 'ART_GROUP_ID', type: 'int'},
{name: 'WHG', type: 'int'},
{name: 'WHG_BEZ', type: 'string'}
]
});
Controller:
public function create()
{
$type = $this->input->get('type', TRUE);
// this parameter comes from ExtJS Extraparam
switch ($type)
{
case 'dnr_type':
$data = $this->dnr->get_dnr_type();
exit(json_encode($data));
case 'dnr_definition':
$para = $this->input->get('dnrtype', TRUE);
$data = $this->dnr->get_dnr_definition($para);
exit(json_encode($data));
case 'article_group_main':
$data = $this->dnr->get_article_group_main();
exit(json_encode($data));
Model:
public function get_article_group_main()
{
$sql = $this->db->query('SELECT ART_GROUP_ID, WHG, CONCAT_WS(" - ", WHG, WHG_BEZ) AS WHG_BEZ FROM MD_ARTICLE_GROUP GROUP BY WHG_BEZ ORDER BY WHG');
return array('articleMainGroup' => $sql->result_array());
}
Here is your request :
{
fieldLabel:'Department',
xtype:'combo',
name:'Department',
forceSelection: true,
typeAhead: true,
allowBlank: false,
emptyText: 'Choose a Department',
store: deptStore,
displayField: 'Name',
valueField: 'Id',
id: 'cmb-department'
}
// Add a listener to the combobox before store load
var combo = Ext.getCmp('cmb-department');
var cmbStore = combo.store;
cmbStore.on('load', function() {
// setValue(777) // here, 777 is unique value that available in the store
combo.setValue(<?php echo $Employee->DepartmentId ?>)
})
I will try to help you but you should correct some mistakes. For instance, you had created data model like below :
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
reader: 'json'
},
fields: [
{name:'Id', type: 'int'},
{name:'Name', type: 'string'}
]
});
But, data model should be :
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'Id', type: 'int'},
...
]
});
So, you should define proxy properties in store config, not data model! The reason is that stores interact with server side, data model just modeling the data.
var deptStore = new Ext.data.JsonStore({
model: 'DeptModel',
proxy: {
type: 'ajax',
url: '<?php echo base_url() ?>Settings/JSON/Departments',
reader: {
type: 'json',
root: 'deptList',
idProperty: 'DEP_ID'
}
}
});
Here, I defined a simple store. You must take notice that root and idProperty properties. You should give a name of the Json object like below :
// return value from model
$sql = $this->db->query('SELECT DEP_ID, ......');
return array('deptList' => $sql->result_array());
// return value from controller
$data = $this->db->get_dept_list($arg);
echo json_encode('$data');
Also, idProperty is important which it should be unique value to be able to eliminate value conflict.
Here is the sample screen shot of my app. As you can see, when an user select a value from DNR TİPİ, app automatically populate the ÌNDİRİM TİPİNİ SEÇİNİZ combobox!
On the screen shot, discDetail equal your deptList.

Linked/chained MagicSuggest dropdowns?

I am trying to build a set of linked/chained multiselect boxes using MagicSuggest and a php query. So, first I build a MagicSuggest box with a function for when ms1 is changed:
$(document).ready(function() {
var ms1 = $('#ms1').magicSuggest({
data: 'datams1.php',
displayField: 'name' });
$(ms1).on('selectionchange', function(event, combo, selection){
run(selection);});
});
Then I build a new MagicSuggest box by running a php query that returns a json object:
function run(country) {
$.getJSON("query.php", { id: country[0].id}, callbackFuncWithData );
}
function callbackFuncWithData(region) {
var ms2 = $('#ms2').magicSuggest({
data: region,
displayField: 'name'
});
}
This works once I make an initial selection, but does not update if I change the selection. I have checked and within my "callbackFuncWithData" I am producing an updated "region" json object. So it might just be that I need to refresh/reload my #ms2 object.
My questions are:
Is there a way to force an refresh of the MagicSuggest data?
Is there a better/cleaner/more efficient way to use the results of one MagicSuggest box to query and return the data for a second, linked MagicSuggest box?
Thanks!
use setData() method to dynamically set the data when needed.
you can always use a library like angular to bind the component properties together.
This code makes 2 linked combos with the same data, but one of them shows the "name" field and the other one shows the "name1" filed.
function reflectSelection(ms1, ms2){
var val = parseInt(ms1.getValue());
var val1 = parseInt(ms2.getValue());
if(!isNaN(val)){
if(val != val1){
ms2.clear(true);
ms2.setSelection(ms1.getSelection());
}
}
else
{
ms2.clear(true);
}
}
var msName = $('#ms-onselectionchange').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
var msName1 = $('#ms-onselectionchange1').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
displayField: 'name1',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
$(msName).on('selectionchange', function(e,m){
reflectSelection(msName, msName1);
});
$(msName1).on('selectionchange', function(e,m){
reflectSelection(msName1, msName);
});

jqGrid errorTextFormat function

I´m developing an application using CodeIgniter and JQuery.
I have read here jqgrid error message on delete and here jqGrid error message from server side exception some issues about this problem but the fact is that does not work for me.
In my database I have set some business rules in form of index, checks, etc. I need to customize the "error Status: 'error'. Error code: 500" that the jqGrid returns when I have those types of errors.
I´d appreciate any help.
Here is my jquery grid code.
<script type="text/javascript">
var base_url = 'http://localhost/sp/';
var site_url = 'http://localhost/sp/index.php';
var url = '';
$(document).ready(function() {
var grid = jQuery("#newapi_1351019084").jqGrid({
ajaxGridOptions : {type:"POST"},
jsonReader : {
root:"data",
repeatitems: false
},
ondblClickRow: function(id){
dtgLoadButton1();
return;
},
rowList:[10,20,30],
viewrecords: true
,url:'http://localhost/sp/index.php/assigment/getData'
,editurl:'http://localhost/sp/index.php/assigment/setData'
,datatype:'json'
,rowNum:'13'
,width:'800'
,height:'300'
,pager: '#pnewapi_1351019084'
,caption:'Control de asignaciones'
,colModel:[
{name:'username',index:'username',label:'Usuario' ,align:'left',width:300,editable:false,edittype:'text',editrules:{required:true} }
,{name:'StoreName',index:'StoreName',label:'Tienda' ,align:'center',width:200,editable:false,edittype:'text',editrules:{required:true} }
,{name:'Users_idUsers',index:'Users_idUsers',label:'Usuario' ,align:'center',width:100,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;5:tienda1;6:tienda2;17:tienda3;18:tienda11",size:10},editrules:{edithidden:true,required:true,integer:true} }
,{name:'Stores_idStores',index:'Stores_idStores',label:'Tienda' ,align:'center',width:100,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;1:EA001;3:EA003;4:EA005;5:EA006;6:EA007;7:EA008;8:EA009;9:EA010;10:EA011;11:EA012;12:EA013;13:EA015;14:EA017;15:EA018;16:EA019;17:EA020;18:EA021;19:EA022;20:EA002;21:EA000",size:10},editrules:{edithidden:true,required:true,integer:true} }
,{name:'SurrugateTurn',index:'SurrugateTurn',label:'SurrugateTurn' ,align:'center',width:100,key:true,hidden:true,editable:true,edittype:'select',editoptions:{value:":Select;1:1;3:3;2:2",size:10},editrules:{hidden:true} }
] })
jQuery("#newapi_1351019084")
.jqGrid('navGrid',
'#pnewapi_1351019084',
{view:false,
edit:'1',
add:'1',
del:'1',
close:true,
delfunc: null ,
search:''
},
{ recreateForm: true,
width : 400 ,
beforeShowForm : function(form) {
},
closeAfterEdit:true }, // edit options
{ recreateForm: true,
width : 400,
closeAfterAdd : true,
beforeSubmit : function(postdata, formid) {
var mensaje = '';
var resultado = true;
return[resultado,mensaje];
}
}, /*add options*/
{mtype: 'POST'} /*delete options*/,
{sopt: ['eq','cn','ge','le' ] ,
multipleSearch: false ,
showOnLoad : false,
overlay:false,mtype: 'POST'} /*search options*/
).navButtonAdd('#pnewapi_1351019084',
{ caption:'', buttonicon:'ui-icon-extlink', onClickButton:dtgOpenExportdata, position: 'last', title:'Export data', cursor: 'pointer'}
);
;
});
</script>
Best regards and thanks for your time,
Assuming the server returns a user-friendly error message with the HTTP 500 response, you can simply to this:
...
{ recreateForm: true,
width : 400 , //removed the empty beforeShowForm callback
errorTextFormat:function(data){
if (data.status == 500)
return data.responseText; // You may need to do some HTML parsing here
}
closeAfterEdit:true }, // edit options
...

Extjs file upload request stays on waitMsg

Through an ExtJs form I am uploading a file for processing in php (csv file in this matter).
The processing all works fine without errors or anything. And as far as I know, all of the other requirement for a proper response are met.
Return message = {success: true}
Response header Content/Type = text/html
Status = 200 OK
However ExtJs keeps showing my WaitMsg instead of going to my success of failure functions
Here is my form:
var form = new Ext.FormPanel({
id : 'mailinglist_form_import',
labelWidth : 210,
fileUpload : true,
border : false,
url : '/plugin/NewsletterManagement/mailinglist/import',
items : [{
xtype : 'fieldset',
width : 560,
border : false,
autoHeight : true,
labelWidth : 215,
defaultType : 'textfield',
defaults : {
width : 307,
labelStyle : 'font-weight: bold;'
},
items : [{
fieldLabel : t('Name') + ' *',
name : 'mli_name',
allowBlank : false
},{
xtype : 'textfield',
fieldLabel : t('File') + ' *',
name : 'file',
inputType : 'file'
}]
}]
});
The button:
var saveBtn = new Ext.Button({
text: t("Save"),
iconCls: 'pimcore_icon_save',
handler: function() {
form.getForm().submit({
waitMsg: t('Saving...'),
success: function () {
var tabpanel = Ext.getCmp("pimcore_panel_tabs");
Ext.MessageBox.alert (t('Message'),t('Data has been saved'));
form.getForm().reset();
grid.getStore().reload();
tabpanel.activate(gridTabId);
tabpanel.remove(tabId);
},
failure: function () {
Ext.MessageBox.alert (t('Message'),t('Saving data failed'));
}
});
}
});
The PHP file contains an echo:
echo "{'success': true}";
Any help is greatly appriciated.
Greetz,
XpertEase
Open console and see the error. If you dont's see both of your alerts -- then it's some error in code, in extjs side. Understand it, fix and then report back.

Categories