How to get rating star value from mysql? - javascript

In my Worklight-based application, I have a rating value(int) stored in mysql. I have as JSON data the rating integer value.
{"storeId":1000,"zipcode":"600014","rating":3,}
Using Jquery I need to display that rating value as images of stars in the application.
If the value is 2, then I need to display 2 star images, and so on.
How can I accomplish this?

It would've been helpful to see what you've implemented thus far (adapter implementation, client-side adapter invocation, ...).
Without it, I can only provide one possible way to get a value from from a database and display it.
It is assumed that:
In your database, there is a 'stars' field and value
In the common\images folder in your application, there is an image of a star
You have created a SQL adapter and configured it correctly
Implementation:
In common\index.html there is, for example, an empty UL element just so that the fetched data will be in a list:
<ul id="usersAndStars"></ul>
In common\js\main.js, you invoke your adapter:
// Of course, you can invoke it whenever you actually want to, and not like below...
function wlCommonInit(){
getStarsFromDatabase();
}
function getStarsFromDatabase() {
var invocationData = {
adapter: 'getStars',
procedure: 'getStars'
};
WL.Client.invokeProcedure(
invocationData,
{
onSuccess: displayStars,
onFailure: failedGettingStars
});
}
Then you handle the response of the invocation, failure and success:
function failedGettingStars() {
alert("failure");
}
function displayStars(response) {
var ul = $('#usersAndStars');
var i, j, li;
for (i = 0; i < response.invocationResult.resultSet.length; i += 1) {
// Create new <li> element and populate it
li = $("<li/>").text("Item " + [i+1] + " has " + response.invocationResult.resultSet[i].stars + " stars: ");
// Add images of a star
// Note that this is purely applicative - instead of adding several img tags,
// You could simply add an image showing 5 or 2 or 3 or however stars you want...
// Or in any other way you want.
for (j = 0; j < response.invocationResult.resultSet[i].stars; j += 1) {
li.append("<img src='images/\star.png' alt='star'/>");
}
// Append the <li> element to the <ul> element
ul.append(li);
};
}
In adapters\getStars\getStars-impl.js file:
var selectStatement = WL.Server.createSQLStatement("select * from users");
function getStars() {
return WL.Server.invokeSQLStatement({
preparedStatement : selectStatement,
parameters : []
});
}
In adapters\getStars\getStars.xml file:
...
...
...
<procedure name="getStars"/>
The end result:

Related

Javascript for Photoshop, weird error it tells me it expects ;,

It tells me it expects ; on the line 60. I got this code from a developer who supposably made it all work but now it does not work on my computer.
This is a script made for photoshop js to execute some action based on the condition whether the layer exists ir not.
So what do you guys think what could it be?
I actually have to write stuff more about this since stackoverflow tells me "your post is mostly code but I have no clue what to write. I could maybe add that the name of the layer where action has to be executed is stored in a variable called workingLayer and the value is read out of the file TITLE.txt which is on the desktop.
function somename(){
#target photoshop
var fileRef = "C:/Users/Dharmindar/OneDrive/Desktop/NAME.txt"
var doc = open(fileRef);
alert(doc);
}
// this function somename is supposably testing if the name.txt can be opened and it gives an alert
// this is anther test function I guess to see how to get layers name or document name I am not sure what he did here
function testFunction() {
var testName = app.activeDocument.name;
var nameWithoutExt = testName.split(".")[0];
nameWithoutExt = nameWithoutExt + ", " + app.activeDocument.layers[0].name;
alert(nameWithoutExt);
}
//here he lists files from folder desktop and then he loops and searches for a file named TITLE.txt. from there he reads the value that he puts into a layer workingLayer. Later he will execute function based on the fact if the layer exists or not.
function SomeOtherFunction() {
//Choose the desired folder
var currentFolder = new Folder('~/desktop/');
//Get files from the selected folder
var currentFiles = currentFolder.getFiles();
var selectedFile;
for (i = 0; i < currentFiles.length; i++) {
if (currentFiles[i] == "~/desktop/NAME.txt") {
selectedFile = currentFiles[i];
}
}
// here he reads the file he opens and equates it to working layer
selectedFile.open("r");
var workingLayer = selectedFile.read();
alert(workingLayer);
var layers = app.activeDocument.layers;
//alert(layers);
for (l = 0; l < layers.length; l++) {
//alert(layers[l].name + " - " + str);
var currentLayer = layers[l].name;
// here he conditions and says if the working layer is equal to the current layer name then execute action exists from custom made 1145Actionset and later he says else, if it does not exist the layer with equal name as working layer then execute action
if(currentLayer.name == workingLayer) {
currentLayer.name = "0";
ExecuteAction("EXISTS","1145ActionSet");
} else {
ExecuteAction("NOTEXISTS","1145ActionSet");
}
RenameLayer("0", workingLayer, layers);
}
}
//here he created function rename layer which is supposed to change layer names after the action has been completed and why was this needed? well it was needed because photoshop actions can not work with variables so what he did he changes the layer name to "0" and then executes action always on layer "0" and then after that he changes the layer 0 back to workingLayer variable value that comes from that TITLE.txt and that is pretty much all there is to it and this weird thing gives me error exactly on the line 60 it says it expects ;
functon RenameLayer(oldName, newName, layers) {
for (var j=0;j < layers.length; j++) {
if (layers[j].name == oldName ){
layers[j].name = newName;
}
}
}
function ExecuteAction(actionName, actionSetName) {
try {
//TO DO IF THE LAYER DOESNOT EXISTS
//Action set must be created first and the action should be in that.
//The first parameter is the name of th action to be performed and the second parameter is the name of th ActionSet
app.doAction(actionName,actionSetName);
} catch(e) {
alert(e);
}
}
SomeOtherFunction();

JQuery Mobile not executing my entire function

I'm trying to add a listview element based on my QR code. So when I scan one QR code, i take the first value of the array, and add a listview element with the text of the first value, and use a counter and so on. However, it doesn't increment my counter. All i get is that the function appendToList() gets terminated once listview refreshes. Count doesnt increment and ArrayIndex remains empty. How can I get the counter to work? And the array as well? The function doesn't execute all the way.
function scan() {
cordova.plugins.barcodeScanner.scan(
function(result) {
$("#nullExhibition").remove();
resetData(); // Removes the empty exhibition text
if (!result.cancelled) {
if (result.format == "QR_CODE") {
var value = result.text;
if(!localStorage.getItem("LocalData"))localStorage.setItem("LocalData","[]")
data = localStorage.getItem("LocalData");
//alert(data);
data = JSON.parse(data);
data.push(value);
localStorage.setItem("LocalData", JSON.stringify(data));
//location.reload();
alert(count);
appendToList();
// location.hash = '#Vote';
}
}
},
function(error) {
alert("Scanning failed: " + error);
}
);
}
//JJJ Function: creates table which will be refreshed in the homePage //CW Create the listview if not created
function appendToList() {
$("#list").append("<li id='" + count + "' style='font-family: 'Quicksand', sans-serif !important;' class='ui-content'><a href='javascript:pageGenerator()'>" + data[0] + "</a></li>");
$("#list").listview("refresh");
ArrayIndex.append(data[0]);
count ++;
}
function resetData(){
localStorage.removeItem("LocalData");
}
Where did you declare "count" in the global scope? You reference it in two separate functions, but are neither passing the value between them, nor made it a global var so that both functions reference the same variable. They way you have it, you reinitialize that var each time that you call the appendToList() function.
Add this to the top of your document (outside of the function closures):
var count = 0;

Twitch TV JSON API Issue

So,I am trying to use the twitch API:
https://codepen.io/sterg/pen/yJmzrN
If you check my codepen page you'll see that each time I refresh the page the status order changes and I can't figure out why is this happening.
Here is my javascript:
$(document).ready(function(){
var ur="";
var tw=["freecodecamp","nightblue3","imaqtpie","bunnyfufuu","mushisgosu","tsm_dyrus","esl_sc2"];
var j=0;
for(var i=0;i<tw.length;i++){
ur="https://api.twitch.tv/kraken/streams/"+tw[i];
$.getJSON(ur,function(json) {
$(".tst").append(JSON.stringify(json));
$(".name").append("<li> "+tw[j]+"<p>"+""+"</p></li>");
if(json.stream==null){
$(".stat").append("<li>"+"Offline"+"</li>");
}
else{
$(".stat").append("<li>"+json.stream.game+"</li>");
}
j++;
})
}
});
$.getJSON() works asynchronously. The JSON won't be returned until the results come back. The API can return in different orders than the requests were made, so you have to handle this.
One way to do this is use the promise API, along with $.when() to bundle up all requests as one big promise, which will succeed or fail as one whole block. This also ensures that the response data is returned to your code in the expected order.
Try this:
var channelIds = ['freecodecamp', 'nightblue3', 'imaqtpie', 'bunnyfufuu', 'mushisgosu', 'tsm_dyrus', 'esl_sc2'];
$(function () {
$.when.apply(
$,
$.map(channelIds, function (channelId) {
return $.getJSON(
'https://api.twitch.tv/kraken/streams/' + encodeURIComponent(channelId)
).then(function (res) {
return {
channelId: channelId,
stream: res.stream
}
});
})
).then(function () {
console.log(arguments);
var $playersBody = $('table.players tbody');
$.each(arguments, function (index, data) {
$playersBody.append(
$('<tr>').append([
$('<td>'),
$('<td>').append(
$('<a>')
.text(data.channelId)
.attr('href', 'https://www.twitch.tv/' + encodeURIComponent(data.channelId))
),
$('<td>').text(data.stream ? data.stream.game : 'Offline')
])
)
})
})
});
https://codepen.io/anon/pen/KrOxwo
Here, I'm using $.when.apply() to use $.when with an array, rather than list of parameters. Next, I'm using $.map() to convert the array of channel IDs into an array of promises for each ID. After that, I have a simple helper function with handles the normal response (res), pulls out the relevant stream data, while attaching the channelId for use later on. (Without this, we would have to go back to the original array to get the ID. You can do this, but in my opinion, that isn't the best practice. I'd much prefer to keep the data with the response so that later refactoring is less likely to break something. This is a matter of preference.)
Next, I have a .then() handler which takes all of the data and loops through them. This data is returned as arguments to the function, so I simply use $.each() to iterate over each argument rather than having to name them out.
I made some changes in how I'm handling the HTML as well. You'll note that I'm using $.text() and $.attr() to set the dynamic values. This ensures that your HTML is valid (as you're not really using HTML for the dynamic bit at all). Otherwise, someone might have the username of <script src="somethingEvil.js"></script> and it'd run on your page. This avoids that problem entirely.
It looks like you're appending the "Display Name" in the same order every time you refresh, by using the j counter variable.
However, you're appending the "Status" as each request returns. Since these HTTP requests are asynchronous, the order in which they are appended to the document will vary each time you reload the page.
If you want the statuses to remain in the same order (matching the order of the Display Names), you'll need to store the response data from each API call as they return, and order it yourself before appending it to the body.
At first, I changed the last else condition (the one that prints out the streamed game) as $(".stat").append("<li>"+jtw[j]+": "+json.stream.game+"</li>"); - it was identical in meaning to what you tried to achieve, yet produced the same error.
There's a discrepancy in the list you've created and the data you receive. They are not directly associated.
It is a preferred way to use $(".stat").append("<li>"+json.stream._links.self+": "+json.stream.game+"</li>");, you may even get the name of the user with regex or substr in the worst case.
As long as you don't run separate loops for uploading the columns "DisplayName" and "Status", you might even be able to separate them, in case you do not desire to write them into the same line, as my example does.
Whatever way you're choosing, in the end, the problem is that the "Status" column's order of uploading is not identical to the one you're doing in "Status Name".
This code will not preserve the order, but will preserve which array entry is being processed
$(document).ready(function() {
var ur = "";
var tw = ["freecodecamp", "nightblue3", "imaqtpie", "bunnyfufuu", "mushisgosu", "tsm_dyrus", "esl_sc2"];
for (var i = 0; i < tw.length; i++) {
ur = "https://api.twitch.tv/kraken/streams/" + tw[i];
(function(j) {
$.getJSON(ur, function(json) {
$(".tst").append(JSON.stringify(json));
$(".name").append("<li> " + tw[j] + "<p>" + "" + "</p></li>");
if (json.stream == null) {
$(".stat").append("<li>" + "Offline" + "</li>");
} else {
$(".stat").append("<li>" + json.stream.game + "</li>");
}
})
}(i));
}
});
This code will preserve the order fully - the layout needs tweaking though
$(document).ready(function() {
var ur = "";
var tw = ["freecodecamp", "nightblue3", "imaqtpie", "bunnyfufuu", "mushisgosu", "tsm_dyrus", "esl_sc2"];
for (var i = 0; i < tw.length; i++) {
ur = "https://api.twitch.tv/kraken/streams/" + tw[i];
(function(j) {
var name = $(".name").append("<li> " + tw[j] + "<p>" + "" + "</p></li>");
var stat = $(".stat").append("<li></li>")[0].lastElementChild;
console.log(stat);
$.getJSON(ur, function(json) {
$(".tst").append(JSON.stringify(json));
if (json.stream == null) {
$(stat).text("Offline");
} else {
$(stat).text(json.stream.game);
}
}).then(function(e) {
console.log(e);
}, function(e) {
console.error(e);
});
}(i));
}
});

Dynamically adjust object names based on parameter

I'm running a script on an apache webserver on a linux box. Based on the parameter I want to change the name of variable(or set it)
The idea is that humDev(lines 11 and 14) is named humDev21 for example. Where devId is the number 21 in this example.
My script looks like this:
function getHumDev(devId){
$.ajax({
async: false,
url: "/url" + devId,
success: function(result) {
var array = result["Device_Num_" + devId].states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
humDev = array[i].value;
}
}
return humDev;
};
objectFindByKey(array, 'service', 'some');
}
});
};
If Im looking in the wrong direction, please do let me know. Maybe its bad practice what Im trying. The reason I want to have the object a unique name is because this function is called several times by another function, based on the content of an array. But when I have the humDev object named without the number suffix to make it unique, the content of the object is getting mixed up between the different calls.
I may be off base but I am making some assumptions based on what I understand of what you are trying to do.
First, you need to understand how to do file I/O in node.js. So lets start there:
var pathToFile, //set with file path string
fs = require('fs'), //require the file i/o module API
bunchOfHumDevs = {},
fileContents; //we'll cache those here for repeated use
fs.readFile(pathToFile, function(err, result) {
if (err) {
throw new Error(); //or however you want to handle errors
} else {
fileContents = JSON.parse(result); //assumes data stored as JSON
}
});
function getHumDev(devId) {
//first make sure we have fileContents, if not try again in 500ms
if (!fileContents) {
setTimeout(function() {
getHumDev(devId);
}, 500);
} else {
var array = fileContents["Device_Num_" + devId].states,
i = array.length,
//if 'service' and 'some' are variable, make them params of
//getHumDev()
while (i--) {
if (array[i]['service'] === 'some') {
//store uniquely named humDev entry
bunchOfHumDevs['humDev' + devId.toString()] = array[i].value;
break; //exit loop once a match is found
}
}
}
return null;
}
getHumDev(21);
assuming a match is found for the devId 21, bunchOfHumdevs will now have a property 'humDev21' that is the object (value?) in question. Also, the fileContents are now cached in the program so you don't have to reopen it every time you call the function.

kendo grid template js with remote datasource

I got a table with remote datasource. in one cell I got the userID. Because I want to show the username instead of the user ID I made a custom template function:
function getUserName(pmcreator){
var user = '';
var data = ''
ds_userList.fetch(function(){
var data = this.data();
for(var i = 0, length = data.length; i < length; i++){
if(data[i].uID == pmcreator){
console.log(data[i].uLastname)
user = data[i].uLastname
}
}
});
return user
}
But its not working as it should, the cells stay empty. I got no errors but I see that the remote request to fetch the usernames is not completed before the grid is filled out. I thought the custom function of fetch is waiting for the results to return but it don't seems so.
Any Idea? I find thousends of examples but all with static local data. I need one with both remote, the grid conent and the template data.
This is probably due the fact that when yuo call the dataSource.fetch it fires off an async function, which causes the thread running the template to continue on. According to kendo you will need to return a control, then set the content of that control inside the callback.
Quick sample using Northwind categories...
Here is the template function
function getDetails(e) {
$.getJSON("http://services.odata.org/V3/Northwind/Northwind.svc/Categories", null, function(data) {
var category = data.value.filter(function(item, i) {
return item.CategoryID === e.CategoryID;
});
$("#async_" + e.CategoryID).html(category[0].Description);
});
return "<div id='async_" + e.CategoryID + "'></div>";
}
http://jsbin.com/ODENUBe/2/edit
I kept getting a recursive error maximum call stack when I just tried to fetch the dataSource, so I switched to a simple getJSON, but it should work pretty much the same.

Categories