Algolia Geo Search Not Working - php
I am having some trouble with Algolia's geo search feature which was working properly before. Here is the record of interest.
I also had that indexed as described by the doc in order for me to sort it by the nearest distance:
'attributesToIndex' => ['name', 'description', 'geo']
In my client script:
let settings = {
aroundLatLng: '10.309813,123.893154',
getRankingInfo: true,
aroundRadius: 2000
};
index.search(keyword, settings, (err, data) => {
console.log(data);
});
But this gives me 0 hit. Notice the aroundLatLng value -- its the same value from the record of interest.
Am I missing something here?
I have implemented same requirement in node.js as per given in document and its working fine.
Here i am copying my whole code. Hopefully it may help you.
Code
/*
I have used async.water model to create the setting of the index and then searching data as per given parameter. few function is custom so no need to bother about that. read each line patently.
*/
try {
var self = this;
var post = req.body;
var user_id = post.user_id;
var created_mode = post.user_mode == 'requester' ? 'provider' : 'requester';
var kword = post.kword;
var geo = post.geo_loc;
var aroundLatLng = post.aroundLatLng;
var aroundRadius = !cmnFn.empty(post.radious) ? post.radious : 4500;
var hitsPerPage = !cmnFn.empty(post.hitsPerPage) ? post.hitsPerPage : 20;
var offset = !cmnFn.empty(post.offset) ? post.offset : 0;
var length = !cmnFn.empty(post.length) ? post.length : 50;
var budget_from = !cmnFn.empty(post.budget_from) ? post.budget_from : 0;
var budget_to = !cmnFn.empty(post.budget_to) ? post.budget_to : 0;
var day_preference = !cmnFn.empty(post.day_preference) ? post.day_preference : '';
var time_preference = !cmnFn.empty(post.time_preference) ? post.time_preference : '';
var start_date = !cmnFn.empty(post.start_date) ? post.start_date : '';
job_index is index created on Algolia
var job_index = algClient.initIndex('jobs');
var cond = {};
If you are using facet & filter then you need to use filter key to execute your condition same as you may have done in sql using where clouse
cond.filters = 'created_mode:"' + created_mode + '" AND (NOT user_id:"' + user_id + '")';
// Query which need to be search
if (!cmnFn.empty(kword)) {
cond.query = !cmnFn.empty(post.kword) ? post.kword : '';
}
if ((!cmnFn.empty(budget_from) && !cmnFn.empty(budget_to)) && budget_from > 0) {
cond.filters += ' AND min_charge: ' + budget_from + ' TO ' + budget_to;
}
if (!cmnFn.empty(day_preference)) {
cond.filters += ' AND day_preference:"' + day_preference + '"';
}
if (!cmnFn.empty(time_preference)) {
cond.filters += ' AND time_preference:"' + time_preference + '"';
}
if (!cmnFn.empty(start_date) && (new Date(start_date)).getTime() > 0) {
cond.filters += ' AND start_date:"' + start_date + '"';
}
Here i am setting aroundLatLng to get data nearest to far
/*
Do not fogot one thing, before using geo search, your records must have _geoloc key having following format
"_geoloc": {
"lat": 40.639751,
"lng": -73.778925
}
*/
// Around geo search by given lat lng
if (!cmnFn.empty(aroundLatLng) && !cmnFn.empty(aroundLatLng.lat)) {
cond.aroundLatLng = aroundLatLng.lat + ', ' + aroundLatLng.lng;
if (!cmnFn.empty(aroundRadius) && cond.aroundRadius > 0) {
cond.aroundRadius = aroundRadius;
}
}
// total number of searched record
if (!cmnFn.empty(hitsPerPage)) {
cond.hitsPerPage = hitsPerPage;
}
// Record starting position
if (!cmnFn.empty(offset)) {
cond.offset = offset;
}
// Page Limitation
if (!cmnFn.empty(length)) {
cond.length = length;
}
// Don't show attributesToHighlight in result set
cond.attributesToHighlight = false;
/*
restrictSearchableAttributes: List of object key, where to search in given list defined in searchableAttributes
*/
cond.restrictSearchableAttributes = [
'user_id',
'title',
'description',
'_geoloc'
];
/*
It will return raning info of result when search come under geo search
Following output will return
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 0,
"userScore": 31,
"geoDistance": 9, // Calculated distance between data geolocation given in _geoloc and search criteria in aroundLatLng
"geoPrecision": 1,
"nbExactWords": 0,
"words": 1,
"filters": 0,
"matchedGeoLocation": {
"lat": 28.5503,
"lng": 77.2501,
"distance": 9
}
}
*/
cond.getRankingInfo = true;
async.waterfall([
function (callback) {
job_index.setSettings({
'attributesForFaceting': ['user_id', 'created_mode', 'min_charge', 'day_preference', 'time_preference', 'start_date'],
/*
searchableAttributes: List of object key , where to search
eg: ['title', 'description']
Like in sql: Where title='your searched text' AND description='your searched text'
_geoloc is reserved keyword of algolia which will used to search geo location
*/
searchableAttributes: [
'title',
'description',
'user_id',
'_geoloc'
],
/*
attributesToRetrieve: Here you can specify list of key name which you want to retrive
eg: ['name','address','age']
Like in sql: Select name, address, age
*/
attributesToRetrieve: [
'*'
]
}).then(() => {
return callback(null, 'success');
});
}
], function (err, results) {
if (err) {
console.log('error: ' + err);
}
job_index.search(cond).then(results => {
if (results.nbHits > 0) {
var rows = new Array();
for (i in results.hits) {
var row = {};
var item = results.hits[i];
var user_info = {};
user_info = item.user_info;
// Get distance and calculate
if (!cmnFn.empty(item._rankingInfo)) {
item.distance = cmnFn.meterToKM(item._rankingInfo['geoDistance']);
} else {
let loc = {
geoLoc_1: { latitude: aroundLatLng.lat, longitude: aroundLatLng.lng },
geoLoc_2: { latitude: item._geoloc.lat, longitude: item._geoloc.lng }
}
cmnFn.getDistance(loc, function (distance) {
item.distance = distance
})
}
/* self.isFav({ user_id: item.user_id, job_id: item.job_id }), function (err, flag) {
item.is_favorite = flag;
}; */
self.isFav({ user_id: item.user_id, job_id: item.job_id }).then(function (flag) {
item.is_favorite = flag;
}, function (err) {
item.is_favorite = false;
});
if (cmnFn.empty(item.currency)) {
item.currency = "₹";
}
//Delete few key from object which does not need to send in response
delete item['user_info'];
delete item['objectID'];
delete item['_geoloc'];
delete item['_rankingInfo'];
row.job_info = item;
row.user_info = user_info;
rows.push(row);
}
info = { status: 1, message: util.format(lang.TOTAL_RECORD_FOUND, results.nbHits), data: rows };
cmnFn.showMsg(res, info);
} else {
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
}
}).catch(err => {
console.log(err);
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
});
//res.end('' + JSON.stringify(results));
});
} catch (error) {
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
}
My bad. Malformed indexed data for _geoloc. Should be keyed with lat and lng
Related
How to check the condition in the jquery?
I am create the js tree to show the folder path name, and my problem is how to check the condition if database table status is 0(inactive) then will show the line-through in the js tree. Else table status is 1(active) just back to normal. Below is my coding: <?php $folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management"); $folders_arr = array(); while($row = mysqli_fetch_assoc($folderData)){ $parentid = $row['parentid']; if($parentid == '0') $parentid = "#"; $selected = false;$opened = false; if($row['id'] == 2){ $selected = true;$opened = true; } $folders_arr[] = array( "id" => $row['id'], "parent" => $parentid, "text" => $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>", "category" => $row['category'], "status" => $row['status'], // status 0 is inactive, status 1 is active "state" => array("selected" => $selected,"opened"=>$opened) ); } ?> <script style="text/javascript"> var StrikeNodes = function(nodelist) { var tree = $('#folder_jstree').jstree(true); nodelist.forEach(function(n) { tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(parseInt(n.text.substr(0, 3), 10)); tree.redraw_node(n.id); //Redraw tree StrikeNodes(n.children); //Update leaf nodes }); }; var getStrike = function(i) { if (status = '0' ) { return "line-through;"; } else { return ""; } }; $('#folder_jstree').bind('load_node.jstree', function(e, data) { var tree = $('#folder_jstree').jstree(true); StrikeNodes(tree.get_json()); }); </script> Now my output show all the all the line-through in the js tree, not detect which is active or inactive. My working JSFiddle code here: https://jsfiddle.net/ason5861_cs/9x0dsotz/3/ Hope someone can guide me which part I am getting wrong.
looking at your code. you are not comparing the status it should be status == '0' instead of status = '0' also there is available option that jstree provided. data option this can be anything you want. it is metadata you want attached to the nod. you will be able to access and modify it any time later - it has no effect on the visuals of the node. [{ "id": "1", "parent": "#", "text": "100 PENTADBIRAN <span id='category'>JTM<\/span>", "category": "JTM", "data": { "status": 0 }, "state": { "selected": false, "opened": false } }] var StrikeNodes = function(nodelist) { var tree = $('#folder_jstree').jstree(true); nodelist.forEach(function(n) { tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(n.data.status); tree.redraw_node(n.id); //Redraw tree StrikeNodes(n.children); //Update leaf nodes }); }; var getStrike = function(status) { if (status == 0) { return "line-through;"; } return ""; }; here's i've edited your fiddle https://jsfiddle.net/Hafizu/1xt7bhem/11/
vue-json-excel containing data issue for multiple excel download
I have the following table in vue component. when click the download button what I need is to download an excel file including multiple data of a Spare Part. So the excel file looks like follows: <download-excel v-if="spare_parts.length" class="btn btn-view" :data="json_data" :fields="json_fields" :title="['Equipments - Spare Part - '+ spare_part.name,'' ]" worksheet="My Worksheet" :name="'Equipments - Spare Part - '+spare_part.name+'.xls'"> <i class="fa fa-download sky-fa" title="Download Report" #click="getReportDetails(spare_part.sap)"></i> </download-excel> json_fields: { 'Equipment - Serial Number': { callback: (value) => { return `${value.maintenance.equipment.serial_number}`; } }, 'Customer Name': { callback: (value) => { return `${value.maintenance.equipment.technical_customer.name}`; } }, 'Unit Price (LKR) - Without VAT': { callback: (value) => { let final = ''; let VAT = ''; let decimalCount = 2; let decimal = "."; let thousands = ","; let amount = `${value.cost}`; try { let decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; final = negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "") // return final; } catch (e) { console.log("Errors " + e); } return final; } }, 'Unit Price (LKR) - With VAT': { callback: (value) => { let final = ''; let VAT = ''; VAT = (`${value.vat}` == 1) ? `${value.cost + (value.cost * (value.vat_percentage / 100))}` : '-'; if (`${value.vat}` == 1) { let decimalCount = 2; let decimal = "."; let thousands = ","; let amount = VAT; try { let decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; final = negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "") } catch (e) { console.log("Errors " + e); } } else { final = '-'; } return final; } }, }, json_data: [], json_meta: [ [ { 'key': 'charset', 'value': 'utf-8' } ] ], when clicking the icon it triggers the getReportDetails(spare_part.sap) function. getReportDetails(name){ axios.get('/technical/sparepart/get-report/'+name) .then(function (response) { this.json_data = response.data; if (this.json_data.length == 0) { alert('No Data in this Spare Part'); } }.bind(this)) .catch(error => { console.log("Errors : " + error); }); }, So the data which need to display inside the excel sheet is getting from this function by calling the following method in the SparePartController: public function getReportDetails($name) { $maintenance_spare_parts = MaintenanceSparePart::with('maintenance.equipment.technicalCustomer')->where('spare_part', $name)->get(); return $maintenance_spare_parts; } I have 2 questions here. When I click on the download icon downloading started at the second time click. But after that every next click the downloading is happening. Why always the second time? After I download I can see the correct data in the excel sheet. But when I click the download icon in another row without page refreshing I'm getting the previous data in my excel file. What's the reason for that? Can anyone point me where I did wrong in this case?
AJAX request from Codeigniter view gives an error
CSRF protection is enabled. I have a view I am trying to insert the shifts to the database table via AJAX. $('#insert_shift').click(function(e) { e.preventDefault(); var empty_td = $('.td_shift[data-type=""]').size(); if (empty_td == 0) { var date = $('#atdnc_date').val() + '-'; var arr = []; var new_arr = []; $('.td_shift').each(function() { //if($(this).attr('data-day') != 0){ var data_type = $(this).attr('data-type'); var shift_atdnc_id = $(this).attr('data-typeid'); var user_id = $(this).attr('data-user'); var new_date = date + $(this).attr('data-day'); if (data_type == 'shift') { var shift_strt_time = $(this).attr('data-start'); var shift_end_time = $(this).attr('data-end'); // Change new_arr to old var new_arr = { 'shift': shift_atdnc_id, 'user_id': user_id, 'date': new_date, 'shift_strt_time': shift_strt_time, 'shift_end_time': shift_end_time, 'checkin_time': '00:00:00', 'checkout_time': '00:00:00', 'time_spent': '00:00:00', 'checkin_reason': 'NA', 'checkout_reason': 'NA', 'work_report': 'NA', 'attn_status': 0 }; } else if (data_type == 'attendance') { var new_arr = { 'shift': shift_atdnc_id, 'user_id': user_id, 'date': new_date, 'shift_strt_time': '00:00:00', 'shift_end_time': '00:00:00', 'checkin_time': '00:00:00', 'checkout_time': '00:00:00', 'time_spent': '00:00:00', 'checkin_reason': 'NA', 'checkout_reason': 'NA', 'work_report': 'NA', 'attn_status': shift_atdnc_id }; } arr.push(new_arr); //} }); $.post(base_url + 'test_shift/insert_shift', { a: arr, csrf_test_name: csrf_token }, function(data) { alert(data); if (data == 1) { document.location.href = base_url + 'test_shift'; } else { alert("error"); } } ); } else { alert("Please fill all the shifts"); } }); If there are only 2 rows of shift, the values are getting inserted. But if there are more, 3 in this case, nothing is getting inserted to db but getting an error in the console. An Error Was Encountered The action you have requested is not allowed. When I did a search on this error I came to know that this is thrown in the case of CSRF issues. But I couldn't find a way to fix the issue. Could someone please help? UPDATE When I changed the order of data in the POST the above error has disappeared. But now another one came up. A PHP Error was encountered Severity: Notice Message: Array to string conversion Filename: mysql/mysql_driver.php Line Number: 589 And a database error. The INSERT query goes like this INSERT into table_name () values ('1','some_value'),('2','some_value2'),Array The code used to generate the array of items is same but from arr[83] the problem starts. I have tried deleting the tds after 83rd day(which is day 23 in 3rd row) from browser and the code worked. I don't understand what is happening here. The 83rd array got chopped for some reason by PHP(or CI).
The issue is fixed. Some elements(starting from array(83)) of the array that is being passed to the controller by the AJAX POST was getting popped, which lead to a database error. I don't know the exact reason yet but after some research I found this thread. So instead of inserting all values in a single INSERT query I have inserted one employee's one month's shift in one insert query, to be safe. Modified the javascript to this $('#insert_shift').click(function(e) { e.preventDefault(); var empty_td = $('.td_shift[data-type=""]').size(); if (empty_td == 0) { var num_of_days = parseInt($('.th_day').last().text()); var num_of_users = parseInt($('.user_shift_row').size()); var insert_helper = 0; var post_finish_helper = 0; var date = $('#atdnc_date').val() + '-'; var arr = []; var new_arr = []; function insert_shift_per_user() { $('.td_shift[data-inserted="0"]').each(function() { insert_helper++; var data_type = $(this).attr('data-type'); var shift_atdnc_id = $(this).attr('data-typeid'); var user_id = $(this).attr('data-user'); var new_date = date + $(this).attr('data-day'); if (data_type == 'shift') { var shift_strt_time = $(this).attr('data-start'); var shift_end_time = $(this).attr('data-end'); // Change new_arr to old var attn_status = 0; var shift = shift_atdnc_id; } else if (data_type == 'attendance') { var shift_strt_time = "00:00:00"; var shift_end_time = "00:00:00"; var attn_status = shift_atdnc_id; var shift = 0; } new_arr = { 'user_id': user_id, 'date': new_date, 'shift': shift, 'attn_status': attn_status, 'shift_strt_time': shift_strt_time, 'shift_end_time': shift_end_time }; arr.push(new_arr); if (insert_helper == num_of_days) { $.post(base_url + 'test_shift/insert_shift', { csrf_test_name: csrf_token, a: arr }, function(data) { if (data == 1) { arr = []; // clearing the array new_arr = []; // clearing the new_array insert_helper = 0; $('.td_shift[data-user="' + user_id + '"]').attr('data-inserted', 1); post_finish_helper++; if (post_finish_helper == num_of_users) { document.location.href = base_url + 'test_shift'; } else { insert_shift_per_user(); } } else { alert("Error"); } } ); } //if insert_helper == num_of_days ends }); } // FUNCTION insert_shift_per_user insert_shift_per_user(); //var aa = jQuery.parseJSON(arr); //console.log(arr); } else { alert("Please fill all the shifts"); } }); //insert_shift ends here
Search bar with jquery dropdown showing results
When the user types something into the search bar I would like the results bellow to link to a page when you click it instead of filling the search bar with whatever you clicked. I'm very new to Jquery and I found this tutorial online but it isn't doing exactly what I wanted it to. Index.php (Just showing some of the head and the body) <script> $(document).ready(function(){ $("#tag").autocomplete("autocomplete.php", { selectFirst: true }); }); </script> </head> <body> <label>Tag:</label> <input name="tag" type="text" id="tag" size="20" style="width:541px; height:23px; font-size:16px; text-indent:5px;" placeholder="Search foods, shopping lists, meal plans and recipes" /> </body> autocomplete.php (Even with the and tags I was unable to achieve the linking to another page.) <?php $q=$_GET['q']; $my_data=mysql_real_escape_string($q); include ("connect.php"); $sql="SELECT id, name, description, foodgroup FROM foods WHERE name LIKE '%$my_data%' ORDER BY name"; $result = mysql_query($sql); if($result) { while($row=mysql_fetch_array($result)) { print "<a href='food.php?foodGroup=" . $row['foodgroup'] . "&name=" . $row['name'] . "&desc=" . $row['description'] . "&foodID=" . $row['id'] . "'><div id='resultContainerDiv'><span id='resultText'>" . $row['name'] . " - " . $row['description'] . "</span></div></a>\n"; } } ?> lastly, jquery.autocomplete.js /* * jQuery Autocomplete plugin 1.1 * * Copyright (c) 2009 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $ */ ;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1; // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { var seperator = options.multipleSeparator.length; var cursorAt = $(input).selection().start; var wordAt, progress = 0; $.each(words, function(i, word) { progress += word.length; if (cursorAt <= progress) { wordAt = i; return false; } progress += seperator; }); words[wordAt] = v; // TODO this should set the cursor to the right position, but it gets overriden somewhere //$.Autocompleter.Selection(input, progress + seperator, progress + seperator); v = words.join( options.multipleSeparator ); } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function(word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $(input).selection(previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else { $input.val( "" ); $input.trigger("result", null); } } } ); } }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.fn.selection = function(start, end) { if (start !== undefined) { return this.each(function() { if( this.createTextRange ){ var selRange = this.createTextRange(); if (end === undefined || start == end) { selRange.move("character", start); selRange.select(); } else { selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } } else if( this.setSelectionRange ){ this.setSelectionRange(start, end); } else if( this.selectionStart ){ this.selectionStart = start; this.selectionEnd = end; } }); } var field = this[0]; if ( field.createTextRange ) { var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength } } else if( field.selectionStart !== undefined ){ return { start: field.selectionStart, end: field.selectionEnd } } }; })(jQuery); Thank you, Ryan
In the search script you have an error: <?php $q=$_GET['q']; $my_data=mysql_real_escape_string($q); include ("connect.php"); mysql_real_escape_string will return false (the equivalent of an empty string) if there is no database connection yet so you are effectively emptying your search string. You need to switch that around: <?php $q=$_GET['q']; include ("connect.php"); $my_data=mysql_real_escape_string($q); You should also add error handling to your database calls and move to PDO or mysqli if possible as the mysql_* functions are deprecated.
PHP jQuery JSON format
I have the following code in PHP which returns this JSON code. I can't return the values for "OK" because of the format, I must do some jQuery trick to get it, but I don't want it... Some advice will be appreciated. PHP while($row = sqlsrv_fetch_array($datBS)) { $ahora = $row['servicio']; if($ahora != $antes && $n == 1) { $ok = array();$ko = array(); $rt = array(); $horas = array(); } if($row['peticion_id'] == 0) {$ok[] = round($row['valor'], 3); $horas[] = $row['hora'];} if($row['peticion_id'] == 1) $ko[] = round($row['valor'], 3); if($row['peticion_id'] == 2) $rt[] = round($row['valor'], 3); $datosBS[$ahora] = array( "OK" => $ok, "KO" => $ko, "RT" => $rt, "HORAS" => $horas ); $antes = $ahora; $n = 1; } while($row = sqlsrv_fetch_array($sqlTotalsBS)) { $bs[$row['servicio']] = array( "SUMOK" => intval($row["OK"]), "SUMKO" => intval($row["KO"]) ); } $banksphere = array_merge_recursive((array)$bs, (array)$datosBS); $json = array_merge((array)$banksphere); echo json_encode($json); JSON {"Servicing":{"SUMOK":923391,"SUMKO":1048,"OK":[184,69,28,14,15,15,0,11,13,0,14,21,19,3,8,0,5,17,13,0,8,30,5,3,13,18,26,24,46,116,342,790,2828,9795,15647,21394,23710,26214,27522,27038,26603,28939,29149,29222,28020,30061,29967,20139,21436,31416,31354,32472,32659,32435,33767,33623,33394,27204,28830,32562,34844,20197,11903,6923,6855,6133,6051,7456,7842,8366,9271,10127,10301,9845,9616,8391],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,9,17,20,11,29,30,35,65,89,56,52,59,26,35,70,39,39,60,28,15,12,27,20,37,20,20,12,8,5,3,8,10,5,12,4,11,9,9,10,11,4],"RT":[0.139,0.171,0.73,0.187,3.667,3.126,0,3.629,7.227,0,4.279,5.967,3.195,2.862,0.883,0,5.441,6.495,0.883,0,1.835,1.656,2.09,0.111,0.35,1.015,1.457,0.829,0.635,0.767,0.534,0.325,0.202,0.172,0.142,0.129,0.125,0.127,0.123,0.125,0.124,0.12,0.122,0.116,0.121,0.114,0.116,0.115,0.116,0.127,0.118,0.128,0.123,0.119,0.12,0.115,0.113,0.114,0.119,0.11,0.104,0.142,0.112,0.139,0.107,0.131,0.149,0.139,0.139,0.133,0.131,0.116,0.109,0.122,0.116,0.113],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Estructurales":{"SUMOK":58088,"SUMKO":453,"OK":[25,12,10,2,16,12,5,11,4,6,10,14,11,7,10,4,7,16,9,6,10,13,9,4,14,10,14,20,33,81,144,366,1562,5956,3671,2251,1976,1960,1600,1656,1475,1396,1473,1567,1412,1486,1553,1198,1046,1655,1636,1743,1711,1550,1417,1340,1562,1312,993,1285,925,790,377,311,286,324,378,486,602,461,542,491,474,450,401,433],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,2,5,11,11,14,10,9,17,10,9,21,10,10,5,8,14,18,16,33,22,18,19,27,21,29,16,13,11,3,2,1,5,5,1,2,3,3,3,2,4,7],"RT":[0.072,0.888,0.085,0.055,0.063,0.065,0.044,0.113,0.046,0.139,0.08,0.215,0.089,0.134,0.083,0.51,0.242,0.224,0.255,0.126,0.125,0.206,0.343,0.062,0.06,0.229,0.074,0.334,0.08,0.186,0.098,0.113,0.141,0.056,0.091,0.165,0.189,0.187,0.211,0.288,0.248,0.267,0.263,0.279,0.296,0.263,0.257,0.266,0.269,0.303,0.294,0.274,0.275,0.284,0.289,0.287,0.297,0.256,0.591,0.25,0.31,0.382,0.25,0.265,0.1,0.115,0.125,0.123,0.132,0.561,0.172,0.254,0.14,0.106,0.193,0.187],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Movilidad":{"SUMOK":96919,"SUMKO":27,"OK":[1563,1396,1250,1082,825,652,427,416,305,266,205,233,149,203,141,118,148,132,101,86,111,141,205,136,285,405,445,584,736,1159,1047,1333,1406,1627,1828,1978,2393,2533,2351,2445,2182,2346,2068,2067,1900,2187,2161,1380,1093,1891,2060,1877,1825,1806,1896,1854,1748,1613,1789,1795,1939,1963,2123,1704,1864,1693,1862,1706,1461,1488,1608,1367,1419,1516,1347,1475],"KO":[1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,0,1,1,0,0,0,0,1,0,2,1,0,0,1,0,2,0,1,2,2,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,4],"RT":[0.361,0.462,0.42,0.417,0.379,0.583,0.43,0.377,0.449,0.505,0.428,0.591,0.466,0.459,0.595,0.441,0.481,0.462,0.65,0.674,0.668,0.519,0.562,0.547,0.52,0.546,0.474,0.481,0.484,0.457,0.449,0.503,0.432,0.425,0.438,0.422,0.441,0.426,0.395,0.397,0.4,0.385,0.408,0.469,0.416,0.45,0.386,0.414,0.413,0.413,0.395,0.373,0.418,0.386,0.387,0.376,0.386,0.398,0.405,0.406,0.399,0.407,0.395,0.385,0.421,0.397,0.372,0.351,0.39,0.384,0.359,0.401,0.403,0.435,0.395,0.355],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Riesgos":{"SUMOK":200875,"SUMKO":1409,"OK":[50,61,31,55,28,26,5,60,20,0,15,0,15,15,0,0,15,0,15,15,0,15,15,0,13,2,0,30,2,44,146,268,510,1265,2425,2955,3841,4581,5321,5587,5944,6327,5300,5337,5291,5679,5805,3869,3708,6929,7262,6740,6493,6381,6789,6080,5504,6053,5190,5224,4327,2092,1426,1499,2065,2972,3495,3766,4504,4265,4429,5289,4926,4524,3760,4185],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,5,5,7,5,17,18,24,24,53,36,47,40,41,43,24,26,53,54,62,58,41,46,51,33,29,26,18,10,13,14,16,21,23,48,53,45,49,34,34,43,38,36,43],"RT":[0.065,0.083,0.13,0.707,0.099,0.084,2.82,0.194,0.22,0,0.492,0,0.433,0.161,0,0,0.298,0,0.537,0.446,0,0.52,0.728,0,0.287,0.345,0,0.082,1.316,1.136,0.352,0.576,0.38,0.27,0.256,0.176,0.179,0.136,0.143,0.152,0.126,0.144,0.13,0.154,0.139,0.151,0.134,0.142,0.153,0.166,0.156,0.147,0.137,0.141,0.129,0.142,0.148,0.132,0.128,0.18,0.124,0.159,0.183,0.154,0.147,0.128,0.135,0.141,0.131,0.175,0.141,0.114,0.14,0.139,0.172,0.162],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Particulares":{"SUMOK":709540,"SUMKO":534,"OK":[5794,5284,4816,3580,3018,2283,2006,1486,1186,1311,918,794,607,677,671,600,412,584,454,506,457,672,665,649,932,894,1412,1727,2158,3063,4326,5923,7038,10129,13647,14923,15905,19339,21463,22762,21936,22069,21976,21072,19951,19413,19256,13127,12318,18637,17980,18297,17357,16708,16401,15354,14515,12789,11771,10628,11232,10458,11007,11007,11753,11383,11922,11604,11120,10776,11697,11471,11463,12479,11531,12011],"KO":[7,8,3,1,7,4,3,1,2,4,2,1,3,0,3,0,0,0,1,1,0,0,2,0,0,0,0,0,0,4,1,5,4,5,7,6,5,5,11,12,17,14,12,13,20,13,12,9,8,21,13,12,15,17,7,13,11,6,9,9,5,12,11,8,10,8,13,8,8,11,7,8,13,20,11,12],"RT":[0.197,0.241,0.204,0.205,0.247,0.241,0.315,0.302,0.178,0.433,0.505,0.181,0.191,0.183,0.228,0.226,0.219,0.326,0.337,0.535,0.273,0.229,0.267,0.218,0.223,0.202,0.219,0.212,0.241,0.191,0.187,0.169,0.2,0.152,0.158,0.171,0.14,0.159,0.149,0.143,0.156,0.146,0.145,0.137,0.141,0.159,0.142,0.158,0.149,0.136,0.133,0.124,0.16,0.145,0.141,0.139,0.143,0.149,0.126,0.132,0.163,0.192,0.181,0.172,0.186,0.147,0.132,0.167,0.138,0.18,0.153,0.146,0.143,0.166,0.142,0.144],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Particulares BKS3":{"SUMOK":799461,"SUMKO":731,"OK":[6917,6108,5726,4223,3433,2683,2391,1693,1304,1253,921,800,688,693,715,634,493,505,426,418,446,743,735,691,1073,984,1672,1881,2260,3230,4607,6421,7692,11239,14628,16550,18563,20975,23237,25076,24469,24579,24123,23419,22116,21400,21976,14099,13843,21162,20687,21039,19535,18668,18566,17750,16300,14561,13380,12424,12500,11909,12463,12460,13241,12829,13668,13038,12602,12539,13516,13739,13601,14415,13847,14271],"KO":[10,6,8,2,2,2,2,7,1,1,0,0,4,0,0,1,0,0,1,0,0,0,0,0,0,0,5,5,3,6,4,8,6,7,7,7,10,14,19,16,17,16,12,18,17,28,23,15,18,18,28,21,23,19,13,11,16,9,15,11,17,10,8,15,23,17,15,8,7,13,15,12,10,18,18,13],"RT":[0.152,0.197,0.156,0.153,0.151,0.199,0.201,0.144,0.149,0.198,0.176,0.34,0.445,0.346,0.406,0.522,0.505,0.405,0.458,0.363,0.297,0.349,0.345,0.216,0.218,0.193,0.2,0.202,0.261,0.525,0.225,0.266,0.17,0.153,0.146,0.148,0.148,0.15,0.154,0.151,0.152,0.155,0.151,0.152,0.142,0.147,0.143,0.142,0.143,0.152,0.148,0.148,0.147,0.151,0.149,0.147,0.141,0.141,0.14,0.144,0.138,0.152,0.141,0.145,0.142,0.144,0.136,0.135,0.136,0.138,0.14,0.144,0.138,0.143,0.143,0.143],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Empresas":{"SUMOK":183051,"SUMKO":658,"OK":[405,389,293,222,254,175,150,182,129,85,78,96,71,85,78,70,70,77,121,77,74,76,102,94,138,149,202,205,371,392,662,958,1269,2478,3425,4178,4458,5982,6565,6905,6723,6242,5983,5989,6005,5467,5452,3187,3855,6037,4980,5874,5682,5283,5166,4975,3949,3239,2753,2354,1884,1819,2065,2305,2645,2640,2954,2835,3068,3017,3068,2997,2682,2849,2599,2639],"KO":[5,0,1,0,6,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,3,0,0,0,1,5,7,12,9,13,9,15,21,22,22,21,17,24,13,17,20,13,17,23,21,13,22,10,13,19,15,6,11,9,8,5,9,7,21,19,9,5,14,27,7,18,10,13,11,15],"RT":[0.145,0.43,0.128,0.141,0.13,0.138,0.087,0.105,0.093,0.219,0.073,0.203,0.158,0.117,0.178,0.109,0.247,0.259,0.472,0.261,0.375,0.159,0.163,0.21,0.252,0.201,0.222,0.707,0.72,0.303,0.341,0.46,0.195,0.132,0.11,0.102,0.104,0.116,0.121,0.102,0.122,0.128,0.131,0.129,0.105,0.102,0.111,0.111,0.11,0.12,0.101,0.112,0.108,0.106,0.112,0.098,0.105,0.141,0.113,0.096,0.089,0.099,0.114,0.12,0.105,0.112,0.1,0.093,0.099,0.138,0.103,0.095,0.108,0.106,0.112,0.098],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Juzgados":{"SUMOK":333138,"SUMKO":102,"OK":[87,59,33,49,59,73,45,63,67,39,46,31,41,58,21,53,32,31,45,30,41,37,21,68,44,138,211,174,47,62,110,393,710,1359,2868,3914,5416,7705,9541,10509,11443,11403,11296,11986,12718,13056,12457,7840,8102,12545,14057,14422,13735,14547,14024,14292,13172,14054,12174,9538,8052,5539,4256,3502,2772,2498,2164,1823,1420,1154,1533,1671,1602,1420,1399,1142],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,7,12,13,13,1,2,6,4,3,13,1,8,4,2,0,0,0,1,1,4,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],"RT":[0.304,0.211,0.108,0.096,0.119,0.101,0.071,0.088,0.085,0.146,0.098,0.093,0.141,0.087,0.082,0.134,0.488,0.141,0.294,0.413,0.116,0.109,0.091,0.191,0.082,0.142,0.104,0.086,0.088,0.149,0.142,0.15,0.146,0.143,0.113,0.114,0.113,0.11,0.11,0.113,0.15,0.176,0.17,0.178,0.118,0.123,0.12,0.129,0.135,0.162,0.111,0.12,0.13,0.111,0.104,0.107,0.105,0.105,0.104,0.102,0.102,0.107,0.097,0.1,0.093,0.112,0.083,0.111,0.086,0.104,0.105,0.114,0.118,0.095,0.115,0.126],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Broker":{"SUMOK":28224,"SUMKO":84,"OK":[71,74,68,78,32,52,39,17,16,11,16,19,1,9,21,17,6,8,1,6,2,69,41,36,59,34,49,37,16,28,42,18,57,75,70,250,413,1222,987,1045,1109,1110,919,926,873,689,876,426,399,529,576,494,531,462,716,681,527,498,475,386,541,619,451,656,608,831,734,791,715,794,1134,1060,334,242,175,225],"KO":[2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,2,9,5,0,2,5,0,1,0,0,4,4,2,1,1,5,1,2,3,0,3,3,1,1,0,3,5,2,3,2,1,0,0,0,3,0],"RT":[0.293,0.716,9.363,0.348,0.363,0.272,0.262,0.213,0.397,1.622,1.954,0.391,4.974,0.728,0.362,1.751,0.501,1.809,0.606,1.114,4.113,0.554,0.418,0.332,0.487,0.244,0.544,0.214,0.23,0.295,0.336,0.242,0.457,0.321,0.457,0.452,0.383,0.439,0.431,0.44,0.469,0.448,0.508,0.463,0.398,0.555,0.46,0.362,0.408,0.426,0.368,0.313,0.316,0.263,0.334,0.318,0.298,0.324,0.493,0.301,0.383,0.345,0.34,0.445,0.313,0.38,0.348,0.324,0.402,0.401,0.476,0.41,0.224,0.22,0.184,0.32],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Sistemas Informacion":{"SUMOK":84657,"SUMKO":282,"OK":[19,19,11,0,6,3,0,6,0,0,6,0,3,3,3,0,3,3,3,3,0,6,3,0,3,6,0,10,70,263,420,872,2529,7961,7513,5454,4559,3310,2970,2652,2740,2444,1807,1600,1960,1825,1666,1188,1299,1429,1684,1668,1291,1213,1438,1347,1324,1385,1355,1377,1344,618,450,347,449,690,972,1157,1200,872,1099,972,1049,969,824,913],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,3,0,2,4,0,1,6,6,0,1,1,12,0,5,3,4,1,22,3,2,4,0,1,0,0,24,101,0,0,2,2,0,1,0,0,2,1,1,33,29,3,1],"RT":[0.437,0.251,0.219,0,2.79,0.3,0,1.323,0,0,1.056,0,1.174,0.659,4.83,0,4.483,4.197,1.64,3.05,0,2.981,0.496,0,0.408,1.601,0,0.662,1.121,1.179,0.325,0.382,0.186,0.222,0.153,0.132,0.133,0.168,0.151,0.15,0.169,0.231,0.16,0.154,0.167,0.182,0.167,0.157,0.152,0.16,0.151,0.192,0.175,0.153,0.199,0.156,0.165,0.158,0.149,0.15,0.136,0.159,0.181,0.205,0.226,0.22,0.253,0.248,0.171,0.212,0.141,0.135,0.153,0.153,0.139,0.152],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Contact Center":{"SUMOK":158998,"SUMKO":216,"OK":[173,44,9,38,63,0,47,6,0,89,19,46,60,11,5,51,2,53,41,13,45,46,11,0,254,65,51,44,9,14,67,52,159,1421,1744,2741,3682,3418,7080,4342,3749,5957,3858,5085,4840,5412,5017,3080,3838,5769,5799,5220,4719,4668,4535,3613,4538,4016,3403,3951,3735,3245,2529,2366,2708,2495,2322,2336,2405,2249,2311,4426,2360,1910,2406,2113],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,4,2,4,2,4,4,7,4,5,15,12,8,3,5,13,14,12,3,5,7,2,9,5,3,4,0,4,6,1,0,3,8,2,1,7,4,2,3,7,4,4],"RT":[0.083,0.128,0.035,0.131,0.085,0,0.174,0.04,0,0.135,0.035,0.134,0.104,0.061,0.642,0.478,0.046,0.135,0.519,0.524,0.129,0.524,0.256,0,0.255,0.08,0.211,0.145,0.066,0.25,0.092,0.146,0.197,0.181,0.176,0.128,0.15,0.134,0.109,0.128,0.113,0.116,0.12,0.114,0.109,0.112,0.101,0.114,0.102,0.181,0.124,0.119,0.101,0.102,0.108,0.106,0.132,0.105,0.111,0.107,0.104,0.1,0.113,0.09,0.091,0.098,0.094,0.098,0.098,0.103,0.085,0.091,0.102,0.084,0.102,0.087],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Cuentas Personales":{"SUMOK":110273,"SUMKO":73,"OK":[173,135,103,98,141,136,150,102,152,136,108,121,164,101,159,137,130,92,128,102,128,141,103,172,134,134,122,122,122,182,160,244,257,345,498,1170,1843,2355,2500,2503,2646,3045,3609,3141,3232,3720,3167,1809,2320,3944,3653,4718,3772,4470,5061,4953,5029,4992,5265,4342,4523,3027,1672,779,373,548,397,476,557,829,1028,519,420,1041,844,549],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,3,1,4,1,2,1,0,5,0,1,2,4,0,2,1,0,5,2,7,1,2,6,2,3,1,0,2,0,1,2,0,4,0,0,0,1,1,1],"RT":[0.419,0.439,0.481,2.572,0.854,0.831,0.547,0.426,0.424,1.022,1.369,0.541,0.523,0.528,0.596,0.5,0.563,1.319,2.444,0.764,2.516,0.506,0.478,0.431,0.452,0.437,0.407,0.482,0.415,0.453,0.95,0.845,0.51,1.378,0.528,0.436,0.486,0.357,0.454,0.45,0.373,0.363,0.421,0.401,0.36,0.388,0.414,0.399,0.375,0.388,0.387,0.393,0.383,0.372,0.395,0.394,0.426,0.421,0.517,0.398,0.478,0.581,0.372,0.463,0.346,0.423,0.436,0.429,0.306,0.41,0.336,0.483,0.379,0.365,0.408,0.412],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"Intervinientes":{"SUMOK":6490,"SUMKO":6,"OK":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,43,79,53,1,251,162,173,265,303,205,342,306,241,482,208,124,170,360,56,294,287,276,354,320,97,140,208,207,114,17,38,4,10,23,6,18,47,18,153,0,16,15,4],"KO":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],"RT":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4.772,1.275,1.027,0.304,0.59,0.327,0.484,0.404,0.361,0.657,0.278,0.264,0.283,0.3,0.284,0.341,0.438,0.283,0.4,0.258,0.312,0.365,0.396,0.336,0.363,1.252,0.377,0.311,0.251,0.827,0.927,2.164,0.388,1.25,0.277,1.239,0.253,1.013,0.639,0,1.085,0.283,0.035],"HORAS":["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45"]},"T4B":{"OK":142975,"KO":2293},"PCAS":{"OK":176,"KO":20}} jQuery Trick var OK = []; $.each(value.OK, function(tipo, valor) { OK = valor; }); // Now if i return OK, it returns me the values... Same for OK, RT ... My question is, I'm missing something on PHP? Because Do the trick on every $datosBS key is a code mess... I think the problem is that "OK" for example, has subarray with the numbers, and JSON doesn't recognize it like "SUMOK" for example, which is plain number instead an array... FULL JQUERY CODE $.getJSON('test.php?entidad_id=2', function(data) { $.each(data, function(key, value) { var pies = { name: key, type: 'pie', data: [], center: [100, 80], size: 100, showInLegend: false, dataLabels: { enabled: false } }; var lineas = { name: "Valores", data: [] }; var renderId = "pie-" + key; $('#charts').append('<div id="'+ renderId +'" class="pieChart"></div>'); lineas.data.push(value.OK); // <------ THIS ISN'T WORKING, EVEN IF I DO ([value.OK]) var OK = []; $.each(value.OK, function(tipo, valor) { OK = valor; }); lineas.data.push(OK); // <----- THIS IS WORKING pies.data.push(["OK", value.SUMOK], ["KO", value.SUMKO]); if(key == "CAM") { pies.data.push(["REJ_OTHERS", value.REJ_OTHERS]); pies.data.push(["REJ_FORMAT", value.REJ_FORMAT]); pies.data.push(["PENDING", value.PENDING]); } options.series.push(pies, lineas); options.chart.renderTo = renderId; options.title.text = key; var chart = new Highcharts.Chart(options); pies.data = null; lineas.data = null; }); });
OK, data in line charts is 2 values [x, y] so the data array is like: [[x1, y1], [x2, y2]], [[1, 2, 3, 4, 5]] doesn't really make sense on a line chart. If you just want to have the index across the x axis and the values along the y axis then you can build your array like: $.each(value.OK, function(i, v) { lineas.data.push([i, v]); }); and just get rid of: lineas.data.push(value.OK); // <------ THIS ISN'T WORKING, EVEN IF I DO ([value.OK]) var OK = []; $.each(value.OK, function(tipo, valor) { OK = valor; }); lineas.data.push(OK); // <----- THIS IS WORKING But without knowing what each data point in OK corresponds to, that is the best I got. Here is a jsFiddle of some working code. Hope this helps! Edit Looks like HORAS may be the time that corrosponds to the OK element, if that is the case you could do: $.each(value.OK, function(i, v) { lineas.data.push([value.HORAS[i], v]); });