fuzzy search (fuse.js) using XML instead of JSON - javascript

Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels

Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});

Related

Push 2 arrays after json loop

I need to run function "testfun 2 times", for each function I will have a few of names lets say testfun(5, global_user) // output [1,2,4,4,5] and for testfun(7, global_user) // output [9,10,11]
How I can put this 2 arrays in one array after I will run 2 functions?
testfun(5, global_user);
testfun(7, global_user);
function testfun(groupId, myUser) {
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: loadTeamNames,
error: errorHandler
}
);
}
var arr = [];
function loadTeamNames(data){
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var name = $(this)[0].Name;
});
}
Thanks
With JS
var mergedArray = outputOne.concat(outputTwo);
With JQuery
var mergedArray = $.merge( $.merge( [], outputOne), outputTwo);
Since testFun() uses asynchronous methods you can't do anything immediately after running it twice without waiting for both instnces to complete. This is accomplished using promises
You could use $when() and return a promise from testFun(). Will need to move loadTeamNames into testFun to do it
$.when() won't complete until both of the promises are resolved
function testfun(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function () {
var name = $(this)[0].Name;
});
// resolve deferred and pass data to be used in `$.when()`
defer.resolve(results);
}
return defer.promise;
}
To use
$.when(testfun(5, global_user),testfun(7, global_user)).done(function (results1, results2) {
//do what you need to with arrays results1 & results2
});
Add defer.reject() in the errorHandler
Assuming that jsonObject.d.results is an array already, you can just do:
arr.concat(results)
This will concatenate your array so far with the new result. Have that code inside of loadTeamNames and each run of testfun will concatenate the result to your current array. not really sure what you're using all those variables inside of loadTeamNames for however.
function getTeamNames(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "$select=Title,LoginName";
var orderbyStr = "$orderby=Title";
var itemsUrl = "https://sites.sp.kp.org/pub/qosstgcat/_api/web/SiteGroups/getbyid(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor(carootUrl);
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var login_name = $(this)[0].LoginName;
});
defer.resolve(results);
}
return defer.promise;
}
result
$.when(getTeamNames(4, global_user),getTeamNames(185, global_user)).done(function () {
console.log(results);
});

how to display json resful data using javascript or jquery

how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});

How to create a JSON feed

I have a file called parsing.html that parses through a xml feed and converts the metadata into JSON Object called "data". I'm trying to output this JSON "data" as a JSON feed such as http://www.videws.com/gtv/videosources.php. Is doing
document.write(JSON.stringify(data)) the equivalent of creating a JSON feed in this case?
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
//document.write(categories);
category.videos.push(video);
}
data.categories.push(category);
}
});
document.write(JSON.stringify(data));
}
})
im not sure you fully understand what http://www.videws.com/gtv/videosources.php is doing.
if you look at the source code it appears not to have any javascript at all so its not doing a document.write, it is more likely doing all of the conversion to JSON within PHP server side then streaming out.
a good help site for using PHP with JSON is available here: http://www.tutorialspoint.com/json/json_php_example.htm
i would say that if your more of a JS/HTML guru you may get more out of NODEJS than PHP but that's entirely up to you.

Set div on get method fail in jquery

I want to set a div's text to "not found" in case the script fails to get the url in the script. I am using jQuery 1.4 version and I have to continue with it for some reason. Can anyone suggest some good ideas?
javascript
$(document).ready(function () {
$("#slides").html("");
$.get('someURl',
function (d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function () {
anchorImg = "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
});
});
1.4 does not have deferred functions so your only option is to convert the $.get to a $.ajax call and use the error handler:
$.ajax({
method: 'GET',
url: 'someURl',
success: function(d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function() {
anchorImg= "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
},
error: function() {
$('#slides').text('Not found');
}
});
You really should be pushing to use the latest version of jQuery though. 1.4 is nearly 4 years out of date!

Illegal invocation when using toArray

I don't have very much to my code but I seem to be getting Illegal invocation with my order variable - works fine and shows in console.log if I comment it out
$('body').on("click", "#brands_by_category_submit_btn", function (e) {
e.preventDefault();
var self = $(this);
var order = $(".order").toArray();
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
if(data.length)
{
var data_array = {
id : id,
brand_name : brand_name,
cat_id : data,
order : order,
state : 1
};
var url = $("#brands_by_category_submit_btn").data("url");
//console.log(data_array);
ajaxCall(url, data_array);
alert("Categories Updated");
}
});
AjaxCall:
function ajaxCall(url, data_array, div_id, callback_fn) {
return $.ajax({
type:'POST',
url:url,
beforeSend: function(){
$("#" + div_id).html("<img src='http://www.#.co.nz/files/large/ajax-loader.gif' alt='Loading..' title='Loading..'/>");
},
data:data_array,
complete:function (data) {
$("#" + div_id).html(data.responseText);
if(callback_fn != null)
{
eval(callback_fn + '()');
}
}
});
}
Your problem is that you're converting an array of HTML elements into POST data which simply isn't possible. You should instead loop through your elements and grab their .text() property:
var self = $(this);
var order = []; //or "new Array()". Whatever you prefer for readability
$(".order").each(function() {
order.push($(this).text());
});
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);

Categories

Resources