solr filtering out and javascript filtering - javascript

when i run solr, I got output like that, but i need show "response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs"} line and all lines have id
this is my html
<div id="response">
<pre class="syntax language-{{lang}} content"><code ng-bind-html="response.data | highlight:lang | unsafe "></code></pre>
<div id="result">
<a ng-show="response.data" id="url" class="address-bar addressblock" ng-href="{{url}}">{{hostPortContext}}{{url}}</a>
</div>`
this is my query.js that In connection with the result (here "data" is result object)
var url = Query.url(params);
Query.query(params, function(data) {
$scope.lang = $scope.query.wt;
if ($scope.lang == undefined || $scope.lang == '') {
$scope.lang = "json";
}
$scope.response = data ;
$scope.filterdata=$filter('uppercase') ($scope.response);
$scope.url = url;
$scope.hostPortContext = $location.absUrl().substr(0,$location.absUrl().indexOf("#"));
});`
and got this result
{
"responseHeader":{
"zkConnected":true,
"status":0,
"QTime":21,
"params":{
"q":"sed",
"_":"1580536766390"}},
"response":{"numFound":4,"start":0,"maxScore":0.21373023,"docs":[
{
"id":"/home/sama/sama_installer/masternode",
"attr_stream_size":["15732"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/masternode"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"language":"en",
...
"_version_":1657306606928396288,
"content":" #!/bin/bash\n#installetion sama project on master\n#cheeke exits sama
{
"id":"/home/sama/sama_installer/start.sh",
"attr_stream_size":["290"],
"attr_x_parsed_by":["org.apache.tika.parser.DefaultParser",
"org.apache.tika.parser.txt.TXTParser"],
"attr_stream_content_type":["application/octet-stream"],
"attr_content_encoding":["ISO-8859-1"],
"attr_resourcename":["/home/sama/sama_installer/start.sh"],
"content_type":"application/x-sh; charset=ISO-8859-1",
"content":" #!/bin/bash\nstart-all.sh\nt=$(cat /var/sama/nodelist)\nfor i in ,
"language":"en",
"content_type_type_s":"application",
"content_type_subtype_s":"x-sh",
"url_ss":["start-all.sh",
"zkServer.sh"],
"_version_":1657306608004235264}]
}}

I am Assuming data realated to your Question. You Can fetch data in following manner. If it return undefined it means there is not parameter named 'id' else 'id' is present
var data = {
"responseHeader": {
"zkConnected": true,
"status": 0,
"id": 101,
"QTime": 21
},
"response": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023,
"id": 102
},
"response1": {
"numFound": 4,
"start": 0,
"maxScore": 0.21373023
}
}
console.log(data.response)
console.log(data.responseHeader["id"])
console.log(data.response["id"])
console.log(typeof(data.response1["id"]) == "undefined") //This way you can check if id is present or not.
if (typeof(data.response["id"]) != "undefined") {
console.log(data.response)
}

Related

getting a specific value from JSON.parse() javascript

Hello I am trying to figure out how to get the "changes" value from
{ data: { sequenceStart: 1613141716565, symbol: 'KCS-BTC', changes: { asks: [Array], bids: [] }, sequenceEnd: 1613141716565 }, subject: 'trade.l2update', topic: '/market/level2:KCS-BTC', type: 'message' }
The data is stored in let data = JSON.parse(msg)
I have tried console.log(data.data.changes) but get undefined, im lost because console.log(data.data) seems to get me part way there but not when I add .changes?
Can you check my code below.
I think your msg is not formated correctly , you can compare with my code
<body >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var msg = '{"data": { "sequenceStart": "1613141716565", "symbol": "KCS-BTC", "changes": { "asks":[["0","0","1613141798456"]],"bids":[]}, "sequenceEnd": 1613141716565 }, "subject": "trade.l2update", "topic": "/market/level2:KCS-BTC", "type": "message" }';
var data = JSON.parse(msg);
console.log(data.data.changes);
var msg1 = '{"sequenceStart":1613141798456,"symbol":"KCS-BTC","changes":{"asks":[["0","0","1613141798456"]],"bids":[]},"sequenceEnd":1613141798456}';
var data1 = JSON.parse(msg1);
console.log(data1.changes);
});
</script>
</body>

Accessing JSON element which has a number for the name

I have tried to access an element of the json structure but can't. I have tried the following.
I am using the npm package json-query to extract part of the bigger JSON object.
var rslt = jsonQuery('results[**][* status=active]', {
data: response
});
var make = JSON.stringify(rslt.value[0]["parms"]["make"])
Bu this does not work, I have also tried to get the following data from the JSON:
var img = JSON.stringify(rslt.value[0]["photos"]["1"]["320x240"]);
var subtitle = JSON.stringify(rslt.value[0]["parms"]["price"]["1"]) + ' EUR';
This is the JSON data I am working with:
{
"value":[
{
"id":7038271775,
"user_id":1307227,
"status":"active",
"title":"",
"url":"https://www.autovit.ro/anunt/nissan-navara-ID7GjS0w.html",
"created_at":"2017-01-06 17:49:35",
"valid_to":"2017-02-03 17:56:16",
"description":"Data inmatriculare: 02.03.2015.\r\n4x4 \r\nABS \r\nAer conditionat \r\nComputer de bord \r\nGeamuri electrice \r\nInchidere centralizata \r\nJante aliaj \r\nRadio CD \r\nServodirectie \r\nVolan multifunctional",
"category_id":29,
"region_id":46,
"city_id":24691,
"city":{
"ro":"Voluntari",
"en":"Voluntari"
},
"coordinates":{
"latitude":44.49192877,
"longitude":26.12458706,
"radius":0,
"zoom_level":16
},
"advertiser_type":"business",
"contact":{
"person":"LeasePlan Outlet Center",
"phone_numbers":[
"0753312151"
]
},
"params":{
"make":"nissan",
"model":"navara",
"year":2014,
"mileage":16785,
"engine_capacity":2500,
"vin":"VSKCVND40U0566467",
"fuel_type":"diesel",
"gearbox":"manual",
"transmission":"all-wheel-lock",
"particle_filter":"0",
"green_tax":"1",
"damaged":"0",
"body_type":"suv",
"door_count":4,
"color":"white",
"metallic":"0",
"pearl":"0",
"matt":"0",
"rhd":"0",
"features":[ ],
"price":{
"0":"price",
"1":15900,
"currency":"EUR",
"gross_net":"net"
},
"vat":"1",
"financial_option":"1",
"leasing_concession":"0",
"date_registration":"2014-1-01",
"registered":"1",
"original_owner":"1",
"no_accident":"0",
"service_record":"0",
"historical_vehicle":"0",
"tuning":"0"
},
"photos":{
"1":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_1_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_1_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_1_148x110.jpg"
},
"2":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_2_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_2_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_2_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_2_148x110.jpg"
},
"3":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_3_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_3_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_3_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_3_148x110.jpg"
},
"4":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_4_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_4_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_4_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_4_148x110.jpg"
},
"5":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_5_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_5_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_5_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_5_148x110.jpg"
},
"6":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_6_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_6_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_6_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_6_148x110.jpg"
},
"7":{
"1080x720":"https://img40.autovit.ro/images_autovitro/820558483_7_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_7_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_7_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_7_148x110.jpg"
},
"8":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_8_1080x720.jpg",
"732x488":"https://img41.autovit.ro/images_autovitro/820558483_8_732x488.jpg",
"320x240":"https://img42.autovit.ro/images_autovitro/820558483_8_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_8_148x110.jpg"
},
"9":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_9_1080x720.jpg",
"732x488":"https://img40.autovit.ro/images_autovitro/820558483_9_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_9_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_9_148x110.jpg"
},
"10":{
"1080x720":"https://img41.autovit.ro/images_autovitro/820558483_10_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_10_732x488.jpg",
"320x240":"https://img40.autovit.ro/images_autovitro/820558483_10_320x240.jpg",
"148x110":"https://img40.autovit.ro/images_autovitro/820558483_10_148x110.jpg"
},
"11":{
"1080x720":"https://img42.autovit.ro/images_autovitro/820558483_11_1080x720.jpg",
"732x488":"https://img42.autovit.ro/images_autovitro/820558483_11_732x488.jpg",
"320x240":"https://img41.autovit.ro/images_autovitro/820558483_11_320x240.jpg",
"148x110":"https://img42.autovit.ro/images_autovitro/820558483_11_148x110.jpg"
}
},
"image_collection_id":820558483,
"last_update_date":"2017-01-24 18:00:26",
"new_used":"used"
}
],
"is_last_page":false,
"is_first_page":true,
"current_page":1,
"total_pages":33,
"current_elements":1,
"total_elements":33
}
I don't know what excatly "json-query" does but I think you can extract any JSON part safely like this;
function dig(input, key) {
var keys = (""+ key).split("."), key = keys.shift();
if (!keys.length) {
return input[key];
}
return dig(input[key], keys.join("."));
}
// here that gives me already without any error thrown >> https://img42.autovit.ro/images_autovitro/820558483_1_320x240.jpg
var p = dig(rslt, "results.0.photos.1.320x240");
console.log(p);
// this is same with
console.log(rslt.results[0].photos[1]["320x240"]);
Credits: https://github.com/yay-couch/couch-js/blob/master/couch/util/util.js#L46
i'm not sure how its not working, the only problem i see with your code is you mistaken by writing params and you write parms

Iterating through JSON objects

I have a little problem with iterating through JSON objects. I have a JSON file which I get with AJAX, I have there 15 objects. In HTML I have a DIV in which are 3 sections: header, body and date. Every 15 sec I should update this sections with data from JSON file.
HTML:
<div class="blog">
<span id="header">
Blog
</span>
<span id="body">
20+ Best Examples of <br>
Coming Soon Page Design
</span>
<span id="date">
May 28, 2013
</span>
</div>
JavaScript:
$(function() {
$.ajax({
url: "news.json",
success: function(result) {
var headCont = $('#header');
var bodyCont = $('#body');
var dateCont = $('#date');
var res = result.news;
$.each(res, function(index, element) {
for (header in res) {
setInterval(function() {
headCont.html(element.header);
}, 15000)
}
});
}
});
});
JSON:
{
"news": [{
"header": "Microsoft is starting a private beta for its iPhone keyboard",
"body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
"date": "2016-04-14T08:40:23.449Z"
}, {
"header": "Microsoft sues U.S. government over data gag orders",
"body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
"date": "2016-03-14T08:40:23.449Z"
}]
}
You should never run interval on AJAX
In your case you only call the server once and loop over the same data
Assuming your JSON works with your loop, perhaps you meant
function updateIt() {
var headCont = $('#header');
var bodyCont = $('#body');
var dateCont = $('#date');
$.ajax({
url: "news.json",
success: function(result) {
var res = result.news;
$.each(res, function(index, element) {
for (header in res) {
headCont.append(element.header);
}
});
});
setTimeout(updateIt,15000); // run after success. use always or complete if needed
}
}
If you need to update the DIV every 15 seconds with the list of stories gotten with ONE AJAX call, then you need to loop with
var news,cnt=0,tId;
function render() {
if (cnt >= news.length) {
clearInterval(tId); // OR set cnt to 0 and do not return to re-iterate
return;
}
var item = news[cnt];
$('#header').append(item.header);
$('#body').append(item.body);
$('#date').append(item.date);
cnt++;
}
$(function() {
.
succes: function(result) {
news = result.news;
render(); // run immediately
var tId = setInterval(render,150000); // and schedule next run
}
.
});
result = {
"news": [{
"header": "Microsoft is starting a private beta for its iPhone keyboard",
"body": "Microsoft has its own mobile operating system, but that hasn't stopped it from opening a public beta for a new iPhone keyboard.",
"date": "2016-04-14T08:40:23.449Z"
}, {
"header": "Microsoft sues U.S. government over data gag orders",
"body": "Microsoft wants a federal court to invalidate part of a 1986 law that it alleged has been abused by the government when authorities demand customers' data.",
"date": "2016-03-14T08:40:23.449Z"
}]
}
var news, cnt = 0, tId;
function render() {
console.log(cnt,news[cnt]);
if (cnt >= news.length) cnt = 0; // rerun
var item = news[cnt];
$('#header').html(item.header);
$('#body').html(item.body);
$('#date').html(item.date);
cnt++;
}
$(function() {
news = result.news;
render();
var tId = setInterval(render, 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header"></div>
<div id="body"></div>
<div id="date"></div>
EDIT
Check this example. It itterates over an array of objects and updates the content every 2 seconds:
var result = [
{ header: 'header0', body: 'body0' },
{ header: 'header1', body: 'body1' },
{ header: 'header2', body: 'body2' },
{ header: 'header3', body: 'body3' },
{ header: 'header4', body: 'body4' },
{ header: 'header5', body: 'body5' },
{ header: 'header6', body: 'body6' },
{ header: 'header7', body: 'body7' }
]
i = 0;
var update = setInterval(function() {
if (result[i]) {
$('#header').html(result[i].header);
$('#body').html(result[i].body);
i++;
} else {
clearInterval(update);
}
}, 2000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Header: <span id="header"></span></h1>
<h1>Body: <span id="body"></span></h1>

Angular: Not able to reach method from scope

I'm trying to use method from my $scope controller, imported from Factory and execute it on onlick method in Ionic based HTML.
I am still getting undefined and I don't know why, because any other variables from $scope are available (like userid). Is this scope hierarchy problem? I read through many articles, but I'm still stuck. Thanks.
Controller:
var mod = angular.module('Baybee.controller.nameList', []);
mod.controller('NameListCtrl', function ($scope, AllNamesList, UidGenerator, $localstorage) {
//importing list of names from Factory and unique user-id
$scope.namesFromService = AllNamesList.getList('AllNamesList');
$scope.userid = UidGenerator;
// test functions which I wasn't able to execute on 'onclick' method. scope.saveName should be that I wanted to use originaly
$scope.saveName = AllNamesList.transferName;
$scope.testb = function () {
console.log('working!');
};
});
Factory:
var mod = angular.module('Baybee.factory.allNamesList',['ionic'])
.factory('AllNamesList', function($localstorage) {
// 3 more list available as variables, here is just one
var AllNamesList = {
names: [
{
"name": "Jakub",
"set": [
"CzechCalendar",
"Top10Cz2015",
"Top50Cz2010"
],
"properties": {
"sex": "male",
"origin": "Hebrew",
"description": "Comes from Hebrew, יַעֲקֹב (Yaʿqob, Yaʿaqov, Yaʿăqōḇ)"
},
"popularity": [
{
"Cz": {
"2011": "10",
"2012": "7",
"2013": "6",
"2014": "6",
"2015": "7"
}
}
]
}
// more names here
]
};
return {
// returns right list with names based on string argument
getList: function(a) {
switch (a) {
case "AllNamesList":
return AllNamesList;
break;
case "loveNameList":
return loveNameList;
break;
case "maybeNameList":
return maybeNameList;
break;
case "noGoNameList":
return noGoNameList;
break;
default:
console.log("Sorry, can't find list with names");
}
},
// I would like to use this function on onlick method to transfer object with name properties to the right list (
transferName: function(name, listFrom, listTo){
// saving both list names into local memory
for (i = 0; i < listFrom.length; i++) {
if (name = listFrom[i]) {
listTo.push(listFrom[i]);
console.log(listFrom);
listFrom.splice(i, 1);
console.log(listTo);
}
else {
console.log('Cannot find: ' + name + ' in ' + listFrom);
}
}
}
}
});
HTML Body:
<body ng-app="baybee">
<ion-pane ng-controller="NameListCtrl">
<ion-header-bar class="bar-energized" >
<h1 class="title" >Baybee</h1 >
</ion-header-bar >
<ion-content >
<ion-list >
<div ng-repeat="names in namesFromService track by $index">
<ion-item ng-repeat="(key, value) in names"
on-swipe-right=""
on-swipe-left=""
//I would like to execute any function from scope here, but Im getting undefined
//onclick="testb()"
//onclick="saveName(name, 'list1', 'list2')"
<h2>{{value.name}}</h2>
<p>{{value.properties.origin}}</p>
</ion-item>
</div>
</ion-list >
</ion-content >
</ion-pane >
</body >
There is mistake in HTML part, I use onclick method, when it should be ng-click.
ng-click="saveName(name, 'list1', 'list2')"
Thanks

Sending specific data to json file from angularJS app using PHP

I have a Library angularJS application and a JSON Data file that contains an array of book's information like this
[
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
},
{
"name" : "test1",
"pages": 0,
"author": "author1",
"year": 1940,
"section": "history",
"current": 0,
"description": "bla bla bla",
"bookUrl": "data/book.pdf"
}
]
"current" is for the current page of the current book that i'm reading
and there is a "next" and "prev" buttons in the reading view
when i press "next" it adds "+1" to the "current" num page
the question is (How to send this +1 to the "current" in JSON file with PHP?)
I have this PHP code :
<?php
$jsonString = file_get_contents('library.json');
$data = json_decode($jsonString, true);
$data[0]['current'] = 3;
$newJsonString = json_encode($data);
file_put_contents('library.json', $newJsonString);
?>
See the ($data[0]) is for the index of the first book, how do i send to PHP the index of the current book so it updates the "current" data of the current book?
Here is the "next" function :
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php")
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
And here is the reading Controller :
app.controller('read', ['$scope','books', '$routeParams',function($scope,books, $routeParams) {
books.success(function(data){
$scope.book = data[$routeParams.bookId]
$scope.pdfUrl = data[$routeParams.bookId].bookUrl;
$scope.pdfName = data[$routeParams.bookId].name;
});
//the pdf viewer options
//$scope.pdfUrl = 'data/tohfa12.pdf';
$scope.scroll = 0;
$scope.loading = 'Loading file please wait';
$scope.getNavStyle = function(scroll) {
if(scroll > 100) {
return 'pdf-controls fixed';
} else {
return 'pdf-controls';
}
};
$scope.onError = function(error) {
console.log(error);
};
$scope.onLoad = function() {
$scope.loading = '';
};
$scope.onProgress = function(progress) {
console.log(progress);
};
$scope.currentBookIndex = parseInt($routeParams.bookId);
}]);
I know it's complicated but i really need that , thanks.
How do you expect your application to behave?
You need to send the bookId and the pageNum with your request!
scope.goNext = function() {
if (scope.pageToDisplay >= pdfDoc.numPages) {
return;
}
scope.pageNum = parseInt(scope.pageNum) + 1;
$http.get("data/insert.php", {
param : {
bookId: $scope.bookId,
pageNum: $scope.pageNum
}
})
.success(function(data, status, headers, config) {
console.log("data inserted successfully");
});
};
BTW. By REST design a GET http request should never change a resource. GET is for READING. If you want to update a resource you should use POST, PUT or DELETE

Categories