How to parse the JSON data from PHP to JS with Mysql? - javascript

I have a JS that generate automatically the select html tag and cascade the 3 dropdowns. Now, I'm trying to get the data of the dropdowns will be filled thru Mysql database with json_encode but I have no luck.
How to parse thejson_encode properly from PHP to JS to fill the dropdown automatically with Mysql?
Please help me.
PHP:
$result_region = $wpdb->get_results('SELECT DISTINCT state, city, avenue FROM tablename', OBJECT);
foreach($output as $rows){
$data[] = array('state'=> $rows->state, 'city' => $rows->city,'avenue'=> $rows->avenue);
}
echo json_encode($data);
Working example of manually encoded data JS:
var data = getData();
var container = document.querySelector("#sl_form");
// initialize select-boxes with data
initSelect(data);
// reads the data and creates the DOM elements (select-boxes and their relevant options)
function initSelect(data) {
var p, select, option, input, filteredOptions;
for (var key in data) {
p = document.createElement("p");
p.innerHTML = key;
select = document.createElement("select");
select.name = key;
container.appendChild(p);
container.appendChild(select);
filteredOptions = optionFilter(data[key].availableOptions, data[data[key].parent], data[key]);
input = document.querySelector('select[name="' + key + '"');
input.setAttribute("onchange", "updateSelect(this)");
for (var i = 0; i < filteredOptions.length; i++) {
option = document.createElement("option");
option.value = filteredOptions[i].value;
option.innerHTML = filteredOptions[i].value;
input.appendChild(option);
}
input.options.selectedIndex = getSelectedIndex(filteredOptions, data[key]);
input.setAttribute('model', data[key].selectedOption.value);
}
}
// this function will be called on change of select-box
function updateSelect(element) {
var input, option;
setSelectedOption(element);
for (var key in data) {
filteredOptions = optionFilter(data[key].availableOptions, data[data[key].parent], data[key]);
input = document.querySelector('select[name="' + key + '"');
while (input.firstChild) {
input.removeChild(input.firstChild);
}
for (var i = 0; i < filteredOptions.length; i++) {
option = document.createElement("option");
option.value = filteredOptions[i].value;
option.innerHTML = filteredOptions[i].value;
input.appendChild(option);
}
input.options.selectedIndex = getSelectedIndex(filteredOptions, data[key]);
input.setAttribute('model', data[key].selectedOption.value);
}
}
// set the selected-option of select-box when it's changed
function setSelectedOption(element) {
var inputName = element.getAttribute("name");
var inputValue = getSelectedText(element);
var inputItem = data[inputName];
var selectedOption, filteredOptions;
// setting selected option of changed select-box
for (var i = 0; i < inputItem.availableOptions.length; i++) {
if (inputValue === inputItem.availableOptions[i].value) {
inputItem.selectedOption = inputItem.availableOptions[i];
break;
}
}
// setting child object selected option now
for (var key in data) {
if (data[key].parent === inputName) {
filteredOptions = optionFilter(data[key].availableOptions, data[data[key].parent], data[key]);
data[key].selectedOption = filteredOptions[0];
}
}
}
// get the text of select-box
function getSelectedText(element) {
if (element.selectedIndex == -1) {
return null;
}
return element.options[element.selectedIndex].text;
}
function getSelectedIndex(options, self) {
var index;
for (var i = 0; i < options.length; i++) {
if (self.selectedOption.value === options[i].value) {
index = i;
break;
}
}
return index;
}
// get filtered options based on parent's selected value
function optionFilter(items, parent, self) {
var result = [];
if (typeof parent !== "undefined") {
for (var i = 0; i < items.length; i++) {
if (typeof parent.selectedOption !== "undefined") {
if (parent.selectedOption !== null && items[i].parentValue === parent.selectedOption.value) {
result.push(items[i]);
}
}
}
if (typeof self.selectedOption === "undefined") {
self.selectedOption = null;
}
if (self.selectedOption === null) {
self.selectedOption = result[0];
}
return result;
} else {
return items;
}
}

Change your foreach loop as below. It will return all value. You were overriding values in foreach loop.
foreach($result_region as $row){
$data[] = ['sl_region'=> $row->sl_region,
'sl_city' => $row->sl_city,'sl_mall'=> $row->sl_mall];
}
if your php version is lower then 5.4 then use
foreach($result_region as $row){
$data[] = array('sl_region'=> $row->sl_region,
'sl_city' => $row->sl_city,'sl_mall'=> $row->sl_mall);
}

Related

LocalStorage set and get using select2 multiple

I'm having a trouble on how can I save and get multiple list in localStorage and retain data to my select. I tried to set and get the item but when the page reload the data does not retain in my select. I also tried printing the list through console.log as you can see in the image the localStorage contain list value . The only problem I encountered , it does not retain the multiple data in my select when reloads. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance!
References:link1
let data = [{"id":1,"name":"USA","parentid":0},
{"id":2,"name":"Japan","parentid":0},
{"id":3,"name":"Europe","parentid":0},
{"id":4,"name":"California","parentid":1},
{"id":5,"name":"Oklahoma","parentid":1},
{"id":6,"name":"Arizona","parentid":1},
{"id":7,"name":"Kantô","parentid":2},
{"id":8,"name":"Kansai","parentid":2},
{"id":9,"name":"Chügoku","parentid":2},
{"id":10,"name":"France","parentid":3},
{"id":11,"name":"Deutschland","parentid":3},
{"id":12,"name":"Espana","parentid":3},
{"id":13,"name":"Sacramento","parentid":4},
{"id":14,"name":"Los Angeles","parentid":4},
{"id":15,"name":"San Diego","parentid":4},
{"id":16,"name":"Tulsa","parentid":5},
{"id":17,"name":"Oklahoma City","parentid":5},
{"id":18,"name":"Lawton","parentid":5},
{"id":19,"name":"Phoenix","parentid":6},
{"id":20,"name":"Flagstaff","parentid":6},
{"id":21,"name":"Tucson","parentid":6},
{"id":21,"name":"Tokyo","parentid":7},
{"id":22,"name":"Chiba","parentid":7},
{"id":23,"name":"Tochigi","parentid":7},
{"id":24,"name":"Kyoto","parentid":8},
{"id":25,"name":"Osaka","parentid":8},
{"id":26,"name":"Nara","parentid":8},
{"id":27,"name":"Tottori","parentid":9},
{"id":28,"name":"Hirochima","parentid":9},
{"id":29,"name":"Okayama","parentid":9},
{"id":30,"name":"Quimper","parentid":10},
{"id":31,"name":"Toulouse","parentid":10},
{"id":32,"name":"Nancy","parentid":10},
{"id":33,"name":"Dusseldorf","parentid":11},
{"id":34,"name":"Leipzig","parentid":11},
{"id":35,"name":"Munchen","parentid":11},
{"id":36,"name":"Barcelona","parentid":12},
{"id":37,"name":"Sevilla","parentid":12},
{"id":38,"name":"Guernica","parentid":12}]
function populateList(list, props) {
if(props[0].value != -1){
let l = document.getElementById(list);
l.innerHTML = "";
let topItem = document.createElement("option");
topItem.value = -1;
topItem.text = "--Select--";
l.appendChild(topItem);
for(let i=0; i< props.length; i++){
let newOptGroup = document.createElement("optgroup");
let item = props[i];
let items = data.filter(it => it.parentid == item.value);
items.forEach(function(it){
let newItem = document.createElement("option");
newItem.value = it.id;
newItem.text = it.name;
if(props.length>0 && props[0].value !=0){
newOptGroup.label= item.key
newOptGroup.appendChild(newItem)
}
else l.appendChild(newItem);
})
if(props.length>0 && props[0].value !=0 && props[0].value !=-1){
l.appendChild(newOptGroup)
}
}
}
}
function updateList(selList, thisList) {
let values = [];
for(let i=0;i<thisList.selectedOptions.length; i++) values.push({
key: thisList.selectedOptions[i].label,
value: parseInt(thisList.selectedOptions[i].value)
})
if (values.length>0 && values[0] != 0) {
populateList(selList, values);
} else {
let s = document.getElementById(selList);
s.value = "";
triggerEvent(s, "onchange");
let sCopy = s.cloneNode(false);
let p = s.parentNode;
p.replaceChild(sCopy, s);
}
}
function triggerEvent(e, trigger)
{
if ((e[trigger] || false) && typeof e[trigger] == 'function')
{
e[trigger](e);
}
}
function loadList1() {
populateList("province[]", [{key: '', value: 0}]);
}
window.onload = loadList1;
function reload_and_saveLocalStorage(){
savedlocalStorage();
gettingLocalStorage();
//reload page
window.location.reload(true);
}
function savedlocalStorage(){
//province setting item to LocalStorage
const province_options = document.getElementById('province[]').options;
var prov_selected = [];
Array.from(province_options).map((option) => {
if (option.selected) {
prov_selected.push(option.value);
}
});
localStorage.setItem("province_localstorage", JSON.stringify(prov_selected));
//municipality setting item to LocalStorage
const muni_options = document.getElementById('municipality[]').options;
var muni_selected = [];
Array.from(muni_options).map((option) => {
if (option.selected) {
muni_selected.push(option.value);
}
});
localStorage.setItem("muni_localstorage", JSON.stringify(muni_selected));
//barangay setting item to LocalStorage
const barangay_options = document.getElementById('barangay[]').options;
var barangay_selected = [];
Array.from(barangay_options).map((option) => {
if (option.selected) {
barangay_selected.push(option.value);
}
});
localStorage.setItem("barangay_localstorage", JSON.stringify(barangay_selected));
}
function gettingLocalStorage(){
//Province getting item to Localstorage and display to select
var province_selected = JSON.parse(localStorage.getItem("province_localstorage"));
const province_options = document.getElementById('province[]').options;
Array.from(province_options).map((option) => {
if(province_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".prov").change();
//Municipality getting item to Localstorage and display to select
var muni_selected = JSON.parse(localStorage.getItem("muni_localstorage"));
const muni_options = document.getElementById('municipality[]').options;
Array.from(muni_options).map((option) => {
if(muni_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".muni").change();
//barangay getting item to Localstorage and display to select
var barangay_selected = JSON.parse(localStorage.getItem("barangay_localstorage"));
const barangay_options = document.getElementById('barangay[]').options;
Array.from(barangay_options).map((option) => {
if(barangay_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".brgy").change();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Region: <select class = "prov" id="province[]" onchange="updateList('municipality[]', this);" multiple="multiple"></select>
Sub-region:<select class="muni" id="municipality[]" onchange="updateList('barangay[]', this);" multiple="multiple"></select>
Location:<select class="brgy" id="barangay[]" multiple="multiple"></select>
<button onclick="reload_and_saveLocalStorage()">SAVE AND RELOAD </button>
Can't execute the snippet beacuse is not secure envolving localStorage, but my advice is to try
$(".brgy").val(option.value);
Instead of setting the "selected" attribute on the option.
That should work.

XML To JSON Conversion with attributes

I am trying to convert the XML to JSON.Here am facing challenge my xml have #attributes name as "value" in all tag. while convert into xml to JSON i am using the below code.
var xml = "<Message><id value="123"></id><type value="Test"></type></Message>"
var json = XMLtoJSON(xml, ["type", "space", "xmlns", "html"]);
var result = JSON.stringify(json)
function XMLtoJSON(xml, ignored) {
var r, children = xml.*, attributes = xml.#*, length = children.length();
if(length == 0) {
r = xml.toString();
} else if(length == 1) {
var text = xml.text().toString();
if(text) {
r = text;
}
}
if(r == undefined) {
r = {};
for each (var child in children) {
var name = child.localName();
var json = XMLtoJSON(child, ignored);
var value = r[name];
if(value) {
if(value.length) {
value.push(json);
} else {
r[name] = [value, json]
}
} else {
r[name] = json;
}
}
}
if(attributes.length()) {
var a = {}, c = 0;
for each (var attribute in attributes) {
var name = attribute.localName();
if(ignored && ignored.indexOf(name) == -1) {
a["_" + name] = attribute.toString();
c ++;
}
}
if(c) {
if(r) a._ = r;
return a;
}
}
return r;
}
Input XML :
<Message><id value="123"></id><type value="Test"></type></Message>
Actual Output:
{"id":{"_value":"123"},"type":{"_value":"Test"}}
Expected Output:
{"id":"123","type":"Test"}
Guide me where am missing the part to get the expected output.
Regards,
nkn1189
do you think if you do this way will work for you?
put your actual output from that parser to this function:
function convertToExpectedOutput(obj){
var result = {}
for (var i in obj){
if (i == "_value")
return obj[i];
else
result[i] = convertToExpectedOutput(obj[i])
}
return result;
}
convertToExpectedOutput(actualOutput)
So, for your array, hange the convertToExpectedOutput to this way and it will give the expected result:
function convertToExpectedOutput(obj){
var result = {}
for (var i in obj){
if (i == "_value")
return obj[i];
else
if (Array.isArray(obj[i])){
result[i] = [];
arr = obj[i]
for (var j in arr)
result[i].push(convertToExpectedOutput(arr[j]))
}
else
result[i] = convertToExpectedOutput(obj[i])
}
return result;
}

Remove object from array object Jquery

I am creating array object like follows:
var numberOfSameDeficiency = [];
for (var i = 0; i < result.length; i++) {
var deficiencyId = result[i].Deficiency_Id;
var deficiencyName = result[i].DeficiencyName;
//check to see if this deficiency is already in the list of available selections
if ($("#drpDeficiency option[value='" + deficiencyId + "']").length == 0) {
var option = $('<option>');
option.attr('value', deficiencyId);
option.text(deficiencyName);
$select.append(option);
}
else {
Tests = {};
Tests.TestId = testId;
Tests.DeficiencyId = deficiencyId;
numberOfSameDeficiency.push(Tests);
}
}
And I want to remove object on different function like this:
for (var i = 0; i < result.length; i++) {
console.log(numberOfSameDeficiency);
var isFound = false;
var deficiencyId = result[i].Deficiency_Id;
if (numberOfSameDeficiency) {
numberOfSameDeficiency.forEach(function (entry) {
if (entry.DeficiencyId != deficiencyId) {
isFound = true;
**numberOfSameDeficiency.splice(entry, 1); // Generating Error (Remove all items from array object)**
return;
}
});
// console.log("end if");
}
if (!isFound) {
$("#drpDeficiency option[value='" + deficiencyId + "']").remove();
}
}
So what line code should be there to remove particular object from array object.
Try this
for( i=myArray.length-1; i>=0; i--) {
if( myArray[i].field == "money") myArray.splice(i,1);
}
This also works
myArray = [{name:"Alpesh", lines:"2,5,10"},
{name:"Krunal", lines:"1,19,26,96"},
{name:"Deep",lines:"3,9,62,36" }]
johnRemovedArray = myArray
.filter(function (el) {
return el.name !== "Krunal";
});
Create this prototype function:
Array.prototype.removeElement = function (el) {
for(let i in this){
if(this.hasOwnProperty(i))
if(this[i] === el)
this.splice(i, 1);
}
}
Then call:
let myArray = ['a','b','c','d'];
myArray.removeElement("c");
It also works with objects:
let myObj1 = {name: "Mike"},
myObj2 = {name: "Jenny"},
myArray = [myObj1, myObj2];
myArray.removeElement(myObj2);

filter objects matching details

Functions works fine, they filter inventory by barcode, and manufacturer. I want to make it like default angularjs filtering. If I choose manufacturer - LG and barcode - 112 and if they don't match, then it shouldn't display anything.
But for now it displays separately, when i click on filter function it filters barcode when on filter2 function filter manufacturer
$scope.filter = function(barcode) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
$scope.filter2 = function(manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
Try this
$scope.filter = function (barcode, manufacturer) {
var filtered = [];
for(var i = 0; i < $scope.inventories.length; i++){
if($scope.inventories[i].barcode == barcode || $scope.inventories[i].manufacturer == manufacturer){
filtered.push($scope.inventories[i]);
}
}
$scope.filtered_inventories = filtered;
};
You could create a more general way of filtering:
$scope.filterByBarcode = function(list, key, value) {
return list.filter(function(item){
return item[key] === value;
});
};
And when you filter you could call:
$scope.filtered_inventories = $scope.filter($scope.filter($scope.inventories, 'barcode', 112), 'manufacturer', 'LG')
But to simplify that you could create a function:
$scope.filterByBarcodeAndManufacturer = function(barcode, manufacturer) {
$scope.filtered_inventories =
$scope.filter($scope.filter($scope.inventories, 'barcode', barcode), 'manufacturer', manufacturer);
}

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

Categories

Resources