Linked/chained MagicSuggest dropdowns? - php

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);
});

Related

select2 drop-down plugin with auto-populate together with add new record

I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.

typeahead bootstrap auto suggestion for ajax function

I'm using typeahead auto suggestion for my application but the problem is ajax function exists in bookingAjaxFunc function and bookingAjaxFunc code is
function bookingAjaxFunc(url, bookingId, jsonCall) {
switch(jsonCall) {
case 'Add':
values = $('.booking-form').serializeArray();
break;
case 'autoSuggestion':
values = {bookingId: bookingId, jsonCall: jsonCall};
break;
}
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: values,
cache: false,
success: function(data) {
switch(jsonCall) {
case 'Add':
console.log(data);
break;
case 'autoSuggestion':
console.log(data);
break
}
}
});
}
this is my ajax function which is working fine in insert, update, delete and other cases but now I want to call this function in typeahead how could I do this? and my typeahead function is working fine in predefined values but now I want to call my bookingAjaxFunc I couldn't figure out where to call my function, and remember this function is copy from an example and I paste it here as it as.
function substringMatcher(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function (i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
}
var states = ['Alabama', 'Alaska'];
$('.autoSuggestion').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
displayKey: 'value',
source: substringMatcher(states)
});
The bookingAjaxFunc function which create for my ajax call so where I use my this code for passing values to my function and use my case
var url = $("#do").val();
bookingAjaxFunc(url, '', 'autoSuggestion');
I also try to add remote below source but didn't work.
Thanks

extjs4 store set extraParam dynamically not working

Good day. I have an unsettling error that I've encountered recently and I do not know where it came from or how it came about.
I have a form where I want to save data to the database upon button press which is handled by the controller. This is what I do in my controller:
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var userId = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'appName.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
console.log("user id to be edited is = " + userId);
console.log("caStore count = " + caStore.getCount());
caStore.getProxy().extraParams = {
selectedUserID: userId
};
// caStore.load();
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
}
});
Here, I set the store extra param in order to use it in the php code query. However, the issue I have is that when I get the selectedUserID in the php code I have, I couldn't seem to get the extra parameter. If I commented out the if(isset($_GET['selectedUserID'])){ .... }, the query works (though the values are hardcoded as of now).
Here is what my store looks like:
Ext.define('app.store.creditApplication', {
extend: 'Ext.data.Store',
requires: [
'app.model.creditApplicationModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.writer.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
model: 'app.model.creditApplicationModel',
storeId: 'creditApplication',
clearOnPageLoad: false,
proxy: {
type: 'ajax',
api: {
create: 'data/person/creditApplication/createCreditApplication.php',
read: 'data/person/creditApplication/readCreditApplication.php',
update: 'data/person/creditApplication/updateCreditApplication.php'
},
url: '',
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json',
encode: true,
root: 'data'
}
}
}, cfg)]);
}
});
Now I'm dumbfounded since I have another code which is similar in the sense that I set the extraParam in the controller and the php code was able to receive and read it just fine. Note that both my stores do not have any extraParam property.
I've been stuck with this problem and I don't know how to go about it. Any help would be greatly appreciated.
Store does not have extraParam(s), proxy does. You can set it with:
store.getProxy().setExtraParam(name, value)

jQuery AJAX request returns object

I have the following AJAX request:
$(function(){
$("#MPrzezn").typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'test',
displayKey: 'value',
source: function(query, process){
$.ajax({
url: 'sprawdzKraj.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
console.log(data);
}
});
}
});
});
... and the following php on backend:
<?php
require_once 'core/init.php';
$user = new User(); //current User
if($user->isLoggedIn()){
if(isset($_POST['query'])){
$query = $_POST['query'];
$delegacja = new Delegacja();
$dataListaDelegacji = $delegacja->listujMiasta($query);
header('Content-Type: application/json');
$json_response = json_encode($dataListaDelegacji);
echo $json_response;
}
} else {
$isLoggedIn = false;
$smarty->assign("userid","",true);
$smarty->assign("isLoggedIn",$isLoggedIn,true);
Redirect::to('login.php');
}
The php script returns a proper json:
[{"ID":"66","IDKraju":"117","NazwaMiasta":"Inowroc\u0142aw","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"251","IDKraju":"117","NazwaMiasta":"\u015awinouj\u015bcie","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"2222","IDKraju":"74","NazwaMiasta":"Rhinow","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"3508","IDKraju":"94","NazwaMiasta":"San Bernardino","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null}]
The picture below shows how the json is being picked up by browser:
There are 4 cities that match the query - each object is a city entry
My goal is to pass values of "NazwaMiasta" to a typeahead input, but I get "undefined" entries. I tried different things but it always keeps showing undefined like this:
Red arrows show all 4 json nodes
I hope I described my problem well. I understand that I'm pretty close, but I cannot find the solution myself. I'll appreciate any help.
Thanks
You have to put right displayKey value!
insted of :
displayKey: 'value',
set :
displayKey: 'NazwaMiasta',
EDIT :
Detailed explanation : When you return data via ajax call, typeahead doesn't know what value to display. So you must set where is value for that key. Your return array of object that have structure like this :
['key1':'value1', 'key2':'value2',...]
By setting ie 'key1' , typeahead knows how to access value ie :
currentElement['key1']...
and than put that value to html.

JqGrid + Autocomplete

I'm having trouble implementing autocomplete in jqgrid. I've walked researching, alias until I based this question on a site that currently do not meet. The problem is this, I have to use the autocomplete several times throughout the application I'm developing. And now I have this function:
Javascript:
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({
source: function(request, response)
{
$.getJSON("autocomplete.php?id=estrategico",
{ q: request.term }, response);
}
});
return $ac;
}
Jqgrid:
jQuery("#obj_oper_org").jqGrid({
(...)
{name:'COD_OBJ_EST',index:'COD_OBJ_EST', hidden: true, editable:true, editrules:{required:true, edithidden:true}, edittype : 'custom', editoptions : {'custom_element' : autocomplete_element}},
What was intended to pass a parameter to the javascript function more in order not to repeat forever the same function for each field because I need to be constantly changing url. Is it possible to make something of the genre? Sorry for the question but I do not have much experience in javascript, so I have some difficulties
First of all you don't need to use edittype : 'custom' to be able to use jQuery UI Autocomplete. Instead of that you can use just dataInit.
You can define myAutocomplete function for example like
function myAutocomplete(elem, url) {
setTimeout(function () {
$(elem).autocomplete({
source: url,
minLength: 2,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).trigger('change');
}
});
}, 50);
}
and then use
{ name:'COD_OBJ_EST', hidden: true, editable: true,
editoptions: {
dataInit: function (elem) {
myAutocomplete(elem, "autocomplete.php?id=estrategico");
}
}}
Be careful that the name of parameter which will be send to the server is the standard name term instead of the name q which you currently use. I personally don't see any need to change the default name of the parameter.

Categories