i am trying to create a relational database while using oop in java script , yet i am encountered with some difficulties , this is the code ,
IT WAS WORKING BEFORE I CHANGED IT TO OOP
function DB() {
this.size;
this.row;
this.getsize = function() {
return this.size;
}
this.db = window.openDatabase('coupons', "1.0", 'database for coupons', 100000);
this.al = function() {
alert('al works');
}
this.add = function(table, id, name, email, fav) {
// alert("works");
// alert("INSERT INTO " + table + " VALUES(" + id + "," + name + ")");
this.db.transaction(function(ob)
{
ob.executeSql("SELECT * FROM " + table + " WHERE pid= " + id + "", [], this.dataHandler, this.errorHandler);
});
this.db.transaction(function(ob)
{
//alert(getsize());
if (this.size > 0) {
alert("user already exists")
} else {
ob.executeSql("CREATE TABLE IF NOT EXISTS " + table + " (pid INTEGER, pname TEXT, pemail TEXT,pfav)");
ob.executeSql("INSERT INTO " + table + " VALUES(" + id + "," + "'" + name + "'" + "," + "'" + email + "'" + "," + "'" + fav + "'" + ")");
alert("user addd successfuly");
}
}
);
}
this.errorHandler = function(error)
{
document.write("handling error " + error);
}
this.dataHandler = function(transaction, data)
{
// document.write("<table>");
//document.write("<tr><th>id</th><th>name</th></tr>")
// size = data.rows.length;
//for(i=0;i<size;i++)
// {
//Variables.call(this,data.rows.length,data.rows.item(0));
//Variables.call(7,6);
this.size = data.rows.length;
this.row = data.rows.item(0);
//return row;
// document.write(
// "<tr><td>"+row['pid']+"</td><td>"+row['pname']+"</td></tr>");
// }
//document.write("</table>");
}
this.getrows = function(n)
{
switch (n)
{
case 'pid':
return this.row['pid'];
break;
case 'pname':
return this.row['pname'];
break;
case 'pemail':
return this.row['pemail'];
break;
case 'pfav':
return this.row['pfav'];
break;
default:
}
}
}
the problem are as follows , hope you can help me out !!
1.after calling the function add , it does not go to dataHandler function .
2. in the add function i am unable to use local variables , how can i use the variable 'size' to check if the user exists in the database or not ?!! ,
hope you can help i have been in this code for 2 days !!! :(
Yes. You obviously can't access this.size in your function because you are using a anonymous function, so this is not related to your DB -oject but points to that anonymous function.
The same for your calls to this.dataHandler or this.errorHandler.
So you could just
this.db.transaction = function(ob)
to make it a method of your object which then will give you full access to the this - pointer of your DB - Object.
EDIT: Sorry, this would then point to the db object, of course, so this is not a solution.
But you can pass it your data - and errorHandler like this:
this.db.transaction(function() { ... }, this.errorHandler, this.dataHandler);
and avoid the call to this.size within the second transaction - statement by simply wrapping your call like:
if(this.size > 0) { alert('..'); } else { db.transaction(...) }
But: Your errorHandler and dataHandler must actually correspond to the right interface - definitions, take a look at:
http://www.w3.org/TR/2009/WD-html5-20090212/structured-client-side-storage.html
Related
I am trying to run the following code which loops through some data from a previous step and then calls a POST fetch command and I am getting the vague "'NoneType' object does not support item assignment" error when I test in Zapier. I have contacted them about it and they cannot support my code and cannot provide any better data on what's happening.
Any ideas?
CODE START
var noteEmail;
var noteSubject;
var noteDescription;
function attachNote() {
fetch ('https://xyzdomain.agilecrm.com/dev/api/contacts/email/note/add', options)
.then(function(res) {
return res.json();
})
.then(function(json) {
callback(null, json);
})
.catch(callback);
}
var headers = {
'Accept': 'application/json',
'Content-Type ': 'application/x-www-form-urlencoded'
};
var dataString = 'email=' + noteEmail + '¬e={"subject":"' + noteSubject + '","description":"' + noteDescription + '"}';
var options = {
method: 'POST',
headers: headers,
body: dataString,
auth: {
'user': 'xyz#xyz.com',
'pass': 'password'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
//Get Rep name by Hubspot ID
function getRep(repNumber) {
switch (repNumber) {
case "12345678":
return "Steve Jenkins";
break;
case "90123456":
return "John Jenkins";
break;
default:
return "Dave Jenkins";
break;
}
}
var dataBody = inputData.Body.split(',');
var dataType = inputData.Type.split(',');
var dataEmailSubject = inputData.EmailSubject.split(',');
var dataCreatedAt = inputData.CreatedAt.split(',');
var dataCreatedBy = inputData.CreatedBy.split(',');
var dataMeetingTitle = inputData.MeetingTitle.split(',');
var dataStartTime = inputData.StartTime.split(',');
var dataEmailBody = inputData.EmailBody.split(',');
var dataEngagementId = inputData.EngagementId.split(',');
for (var i = 0; i < dataEngagementId.length; i++) {
switch (dataType[i]) {
case "NOTE":
noteSubject = "HS NOTE: - " + dataCreatedAt[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataBody[i];
attachNote();
break;
case "MEETING":
noteSubject = 'HS MEETING: - ' + dataStartTime[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataMeetingTitle[i];
attachNote();
break;
case "TASK":
noteSubject = 'HS TASK: - ' + dataCreatedAt[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataBody[i];
attachNote();
break;
case "CALL":
noteSubject = 'HS CALL: - ' + dataCreatedAt[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataBody[i];
attachNote();
break;
case "EMAIL":
noteSubject = 'HS EMAIL: - ' + dataCreatedAt[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataEmailSubject[i]; + ' - ' + dataEmailBody[i];
attachNote();
break;
case "INCOMING_EMAIL":
noteSubject = 'HS INCOMING EMAIL: - ' + dataCreatedAt[i] + " - " + getRep(dataCreatedBy[i]);
noteDescription = dataEmailSubject[i]; + ' - ' + dataEmailBody[i];
attachNote();
break;
default:
//Nothing matches do nothing
break;
}
}
David here, from the Zapier Platform team.
Your code is syntactically correct, so you're good to go there. Standard (my preferred js linter; powered by eslint) noted that there's some unreachable code, but that's not a showstopper. In your getRep function, you've got code after return (just break, no big deal) which will never be called. return quits the entire function, so it replaces the break you would normally need.
As for your actual issue, you're re-defining callback when you shouldn't be. There's docs on the issue, but the idea is that that's a function that lambda (where your code is run) defines. Redefining breaks the code runner.
Sorry for the confusion here! I'll see about throwing an error in the parser if you do this (or surfacing a better error).
Separately, I'm not positive this will do what you expect. Namely, you use noteSubject and noteDescription in dataString towards the top of the function, but modify it later. I don't think these changes will be shown in the options object. I haven't run your code though, so if fixing your callback redefinition makes everything work, ignore my suggestions. Also, to no-op the rest of the function, you can return [] per these docs.
Hope this helps. Let me know if you've got any other questions!
Is this even possible?
function from_country_to_country(country_from, country_to) {
// get the right zone prices
var zone_price = zone_finder(country_to['zone']);
$('#country_to_country').html(country_from['land']);
$('#call').html(formatPrice(country_from[zone_price]) + ' kr/min');
$('#recieve').html(formatPrice(country_from['receive_calls']) + ' kr/min');
$('#send_sms').html(formatPrice(country_from['send_sms']) + ' kr/SMS');
$('#recieve_sms').html(formatPrice(country_from['receive_sms']) + ' kr/SMS');
$('#opening_fee').html(formatPrice(country_from['opening_fee']) + ' kr');
}
function within_the_country(country) {
$('#from_within').html(country['land']);
$('#from_domestic').html(formatPrice(country['domestic']) + ' kr/min');
$('#from_RCF').html(formatPrice(country['receive_calls']) + ' kr/min');
$('#from_send_sms').html(formatPrice(country['send_sms']) + ' kr/SMS');
$('#from_recieve_sms').html(formatPrice(country['receive_sms']) + ' kr/SMS');
$('#from_opening_fee').html(formatPrice(country['opening_fee']) + ' kr');
$('#from_gprs_data').html(formatPrice(country['data_price'])+ ' kr/mb');
}
// Format prices from ex: turns 1 into 1,00
function formatPrice(n) {
if (!isNaN(parseFloat(n))) {
n = parseFloat(n);
n = Math.round(n * 100) / 100
n = n.toFixed(2);
return n;
} else {
// IF WE CAN MAKE "n" NON-APPENDABLE HERE
return n;
}
}
If n is not a number I dont want ' kr/mb' to be appended to the string. I know that I can check if it is a number and if not, dont append. But I have many different suffixes that I append onto the returning string of formatPrice(). So then I will need to check this everywhere. Is there a nice work around to this?
Adjust your formatPrice function to conditionally take in a unit:
function formatPrice(n, unit) {
if(!isNan(...)) {
...
return n + " " + unit;
}
else {
return n;
}
}
formatPrice(500, 'kr/mb');
I am currently learning SignalR with .Net MVC and following a tutorial to work on a simple app. Right now it is working alright, but I am having trouble understanding some part and also if possible, want to sort of enhance it.
Plane Seats Tutorial link
Right now the app is working as when a user clicks on a seat, it reserves it. And there is no going back. I want to implement like a toggle, where if the user wants to change seat, he gets to unreserve his selected seat, and then be free to reserve another one. I am not being able to do it with myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));. Whenever I click on a seat, it gives me this error in the Dev tools
Uncaught: Converting circular structure to JSON
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
$(function() {
//// Start the hub
window.hubReady = $.connection.hub.start();
});
$.connection.hub.start().done(function() {
// Call the server side function AFTER the connection has been started
myHub.server.createUser();
//invoke for the user data
myHub.server.populateSeatData();
});
// Seat selection
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('Sorry, this seat has been already reserved');
} else {
//$(this).toggleClass(settings.selectingSeatCss);
//myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));
myHub.server.selectSeat(userId, $(this)[0].innerText);
}
});
// Client method to broadcast the message
myHub.client.createUser = function(message) {
userId = message;
};
//get seats data
myHub.client.populateSeatData = function(message) {
var parsedSeatsData = JSON.parse(message);
$('li.seat').removeClass(settings.selectedSeatCss);
$.each(parsedSeatsData, function(index, value) {
$("a:contains('" + value.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
});
};
// Client method to broadcast the message as user selected the seat
myHub.client.selectSeat = function(message) {
var parsedSeatData = JSON.parse(message);
$("a:contains('" + parsedSeatData.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
};
And can anyone please briefly explain what is str.push doing in this block of code? What is it exactly pushing into the array?
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 2; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' + 'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' + '<a title="' + seatNo + '">' + seatNo + '</a>' + '</li>');
}
}
$('#place').html(str.join(''));
};
I had to use a toggleSeat() function instead of just using toggleClass.
public void toggleSeat(int userId, int seatNumber)
{
PlaneSeatArrangment mySeat = allSeats.Where(s => s.SeatNumber == seatNumber).FirstOrDefault();
var retunData = JsonConvert.SerializeObject(mySeat);
if (mySeat != null && userId == mySeat.UserId)
..............
}
I am writing code to generate thumbnails based on user selected image manipulation actions which may be multiple as choosen by user using lwip npm package module.
For multiple actions lwip provides batch function and then chaining other manipulating functions.The problem i faced is that user may select any combination of host of manipulating functions and it is too cumbersome to check for each and every combinations of selected actions.
So, i have generated the code dynamically as js code string which i need to execute as function without using eval that may compromise application security
Below is my code
'use strict';
(function(uploadhandler){
var lwip=require('lwip'),
imageSettingProvider=require('../data/imagesettingprovider'),
uploadFolder='public/uploads/',
imageManipulatorHelper=require('./imagemanipulationactions'),
manipulatedImage='';
uploadhandler.generateThumbnail=function(filePath,filename,ImageUploadSetting,fs){
// compound effects
var thumbnailPath='';
lwip.open(filePath, function(err, image) {
if (err) {
console.log(err);
}else{
imageSettingProvider.getImageSetting(ImageUploadSetting,{},function(err,imageSettings){
imageSettings.forEach(function(element,index,array){
thumbnailPath=uploadFolder + element.folderName + '/' + filename;
var imageAction=element.action;
if(imageAction.indexOf(',')>-1){
var imageManipulationActions=imageAction.split(',');
var manipulationHtml='';
manipulationHtml += 'image.batch()';
var actionHtml='';
imageManipulationActions.forEach(function(actionelement,actionindex,actionarray){
actionHtml += uploadhandler.PerformMultipleImageManipulation(actionelement,element,actionHtml);
});
manipulationHtml += actionHtml;
console.log('----------------------------------------------------------------------------------------------------------');
manipulationHtml += '.writeFile(thumbnailPath, function(err) { if (err) throw err;});';
console.log(manipulationHtml);
}
});
});
}
});
};
uploadhandler.PerformMultipleImageManipulation=function(imageAction,imageOpts,actionHtml){
switch (imageAction){
case "crop":
actionHtml = '.crop(' + imageOpts.width + ',' + imageOpts.height + ')';
break;
case "cropbycoordinates":
actionHtml = '.crop(' + imageOpts.cropLeftPos + ',' + imageOpts.cropTopPos + ',' + imageOpts.cropRightPos + ',' + imageOpts.cropBottomPos + ')';
break;
case "resize":
actionHtml = '.resize(' + imageOpts.width + ',' + imageOpts.height + ')';
break;
case "resizecrop":
actionHtml = '.resize(' + imageOpts.width + ',' + imageOpts.height + ')' + '.crop(' + imageOpts.width + ',' + imageOpts.height + ')';
break;
case "rotate":
actionHtml = '.rotate(' + imageOpts.rotateDegree + ',' + imageOpts.backgroundColor + ')';
break;
case "blur":
actionHtml = '.blur(' + imageOpts.blurVal + ')';
break;
case "scale":
actionHtml = '.scale(' + imageOpts.scaleVal + ')';
break;
case "mirror":
actionHtml = '.mirror(' + imageOpts.flipAxes + ')';
break;
case "fade":
actionHtml = '.fade(' + imageOpts.fadeVal + ')';
break;
}
return actionHtml;
};
})(module.exports);
Now when i log the manipulation variable to the console,it gives:
image.batch()
.resize(480,320)
.crop(480,320)
.rotate(75,white)
.writeFile(thumbnailPath, function(err) {
if (err) throw err;
});
Now i need to execute this above js code string as function to generate thumbnail image without using javascript eval function.
I have tried using following approach from sitepoint website:
// function we want to run
var fnstring = "runMe";
// find object
var fn = window[fnstring];
// is object a function?
if (typeof fn === "function") fn();
But it gives me with the error " ReferenceError: window is not defined
"
Please guide me to solve this problem.
Fetch the actions into global object and execute each one using each particular function's namespace.
var helper = {};
helper.b = function() {
console.log("foo");
}
helper.c = function() {
console.log("bar");
}
//execute them
function execute(key) {
try {
helper[key]();
} catch (e) {
throw new Error("Function does not exist");
}
}
execute("b");
execute("c");
execute("d");
If it helps, you could run a regex replace function.
Note: I have not tested this.
// if worried about security with eval, you may want to put functions in an object instead of using global
const myFunctions = {
runMe: function(){/* do stuff */},
runMe2: function(){/* do stuff */}
};
const allowedFuncs = ['runMe', 'runMe2'];
// or dynamic to entire object
const allowedFuncs = Object.keys(myFunctions);
str = str.replace(new RegExp('(''+allowedFuncs.join('|')+)\\((.*?)\\)', 'g'), (str, func, attrs) => {
// check allowed list for added security
if(allowedFuncs.includes(func)){
attrs = attrs.split(',');
myFunctions[func](...attrs); // 3 dots makes js expand array to params separated by camas
}
return str; // returning str replaces nothing
});
This is just freakin weird to me. So if I don't
function BindAlbumAndPhotoData()
{
// Get an array of all the user's Albums
var aAlbums = GetAllAlbums(userID, token);
alert("aAlbums: " + aAlbums);
if (aAlbums == null || aAlbums == "undefined")
return;
// Set the default albumID
var defaultAlbumID = aAlbums[0].id;
};
So I get an undefined error on the line var defaultAlbumID = aAlbums[0].id; if I don't uncomment the alert("aAlbums: " + aAlbums);
what the heck? If I comment out alert("aAlbums: " + aAlbums); then I get an undefined for the var defaultAlbumID = aAlbums[0].id;
This is so weird. I've been working all night to figure out why I kept getting an undefined for the aAlbum[0] and as soon as I add back an alert that I used to have above it, all is fine...makes no sense to me.
Here's the full code of GetAllAlbums:
function GetAllAlbums(userID, accessToken)
{
var aAlbums = []; // array
var uri = "/" + userID + "/albums?access_token=" + accessToken;
alert("uri: " + uri);
FB.api(uri, function (response)
{
// check for a valid response
if (!response || response.error)
{
alert("error occured");
return;
}
for (var i = 0, l = response.data.length; i < l; i++)
{
alert("Album #: " + i + "\r\n" +
"response.data[i].id: " + response.data[i].id + "\r\n" +
"response.data[i].name: " + response.data[i].name + "\r\n" +
"response.data[i].count: " + response.data[i].count + "\r\n" +
"response.data[i].link: " + response.data[i].link
);
aAlbums[i] = new Album(
response.data[i].id,
response.data[i].name,
response.data[i].count,
response.data[i].link
);
alert("aAlbums[" + i + "].id : " + aAlbums[i].id);
}
});
return aAlbums;
}
so I'm not returning the array until I hit the callback of the FB.api async call so I don't see how my defaultAlbumID = aAlbums[0].id; line of code is executing before I have a valid array of data back. When I put in the alert, ovbvioulsly it's delaying before it hits my line defaultAlbumID = aAlbums[0].id; causing it to I guess luckily have data beacuse the async FB.api call is done but again I don't see how that's even possible to have an issue like this when I'm waiting for the call before proceeding on and returning the array to aAlbums in my BindAlbumAndPhotoData() method.
UPDATE #3
function BindAlbumAndPhotoData()
{
GetAllAlbums(userID, accessToken, function (aAlbums)
{
alert("we're back and should have data");
if (aAlbums === null || aAlbums === undefined) {
alert("array is empty");
return false;
}
var defaultAlbumID = aAlbums[0].id;
// Set the default albumID
var defaultAlbumID = aAlbums[0].id;
// Bind the album dropdown
alert(" defaultAlbumID: " + defaultAlbumID);
});
};
function GetAllAlbums(userID, accessToken, callbackFunctionSuccess)
{
var aAlbums = []; // array
var uri = "/" + userID + "/albums?access_token=" + accessToken;
FB.api(uri, function (response)
{
// check for a valid response
if (!response || response.error)
{
alert("error occured");
return;
}
for (var i = 0, l = response.data.length; i < l; i++)
{
alert("Album #: " + i + "\r\n" +
"response.data[i].id: " + response.data[i].id + "\r\n" +
"response.data[i].name: " + response.data[i].name + "\r\n" +
"response.data[i].count: " + response.data[i].count + "\r\n" +
"response.data[i].link: " + response.data[i].link
);
aAlbums[i] = new Album(
response.data[i].id,
response.data[i].name,
response.data[i].count,
response.data[i].link
);
alert("aAlbums[" + i + "].id : " + aAlbums[i].id);
}
// pass the array back to the callback function sent as a param to the GetAllAlbums method here
callbackFunctionSuccess(aAlbums);
});
}
It's not hitting my alert in the callback. I must still be doing something wrong here.
UPDATE #4 - for some reason it's not hitting my FB.api callback now.
function GetAllAlbums(userID, accessToken, callbackFunctionSuccess)
{
var aAlbums = []; // array
var uri = "/" + userID + "/albums?access_token=" + accessToken;
alert("uri: " + uri);
FB.api(uri, function (response)
{
// check for a valid response
if (!response || response.error)
{
alert("error occured");
return;
}
for (var i = 0, l = response.data.length; i < l; i++) {
alert("Album #: " + i + "\r\n" +
"response.data[i].id: " + response.data[i].id + "\r\n" +
"response.data[i].name: " + response.data[i].name + "\r\n" +
"response.data[i].count: " + response.data[i].count + "\r\n" +
"response.data[i].link: " + response.data[i].link
);
aAlbums[i] = new Album(
response.data[i].id,
response.data[i].name,
response.data[i].count,
response.data[i].link
);
alert("aAlbums[" + i + "].id : " + aAlbums[i].id);
}
alert("about to pass back the array to the callback function");
// pass the array back to the callback function sent as a param to the GetAllAlbums method here
callbackFunctionSuccess(aAlbums);
});
}
function BindAlbumAndPhotoData()
{
// Get an array of all the user's Albums
GetAllAlbums(userID, token, function(aAlbums){
// Set the default albumID
var defaultAlbumID = aAlbums[0].id;
});
};
and then in the GetAllAlbums function call the success function when you have the data back
//********* AFTER THE BREAK *******//
In response to the updated question: The FB API is mostly asynchronous, and will keep executing other code while it waits. So using your code, all I have done is passed in the function, and then call the function you've passed it at the end
function GetAllAlbums(userID, accessToken, funcSuccess)
{
var aAlbums = []; // array
var uri = "/" + userID + "/albums?access_token=" + accessToken;
alert("uri: " + uri);
FB.api(uri, function (response)
{
// check for a valid response
if (!response || response.error)
{
alert("error occured");
return;
}
for (var i = 0, l = response.data.length; i < l; i++)
{
alert("Album #: " + i + "\r\n" +
"response.data[i].id: " + response.data[i].id + "\r\n" +
"response.data[i].name: " + response.data[i].name + "\r\n" +
"response.data[i].count: " + response.data[i].count + "\r\n" +
"response.data[i].link: " + response.data[i].link
);
aAlbums[i] = new Album(
response.data[i].id,
response.data[i].name,
response.data[i].count,
response.data[i].link
);
alert("aAlbums[" + i + "].id : " + aAlbums[i].id);
}
funcSuccess(aAlbums);
});
}
Is your function GetAllAlbums() doing some HTTP requests? If so then you need to either make that call synchronous or you need to put your code into a function and pass that as a callback to the Ajax request.
Try three equals signs instead of two, and also... return false rather than nothing at all.
if (aAlbums === null || aAlbums === undefined)
return false;
Also, undefined doesn't need to be in quotes, otherwise, it's just considered a string with a value of "undefined"
On an added note, it's probably better to ALSO check if aAlbums is actually an array before you decide to return a key from it.
if ( aAlbums === null
|| aAlbums === undefined
|| (typeof(aAlbums)=='object'&& !(aAlbums instanceof Array))
} return false;
Try modifying your condition like this:
if (typeof aAlbums == 'undefined')
return;
Also make sure that aAlbums has values and is an array:
alert(aAlbums.length);
Or:
for(var i = 0; i < aAlbums.length; i++)
{
alert(aAlbums[i].id);
}