Failure when pass param between functions in js - javascript

when i launch my applicattion appears the next failure: "record is null or is not an object", appears in the next line " var record = context.record;" Somebody could explain or find the failure... i try to pass the var "mola" from beforeedit to the edit function...
My code is the next:
listeners: {
beforeedit:
function preditar(editor, e, eOpts, mola) {
var grid = Ext.getCmp('gridTabla'); // or e.grid
var hoy = new Date();
dia = hoy.getDate();
if(dia<10)
{
dia=String("0"+dia);
}
mes = hoy.getMonth();
if(mes<10)
{
mes=String("0"+mes);
}
anio= hoy.getFullYear();
fecha_actual = String(anio+""+mes+""+dia);
//alert(fecha_actual);
var mola = e.record.data.ESTLOT;
//alert(mola);
editar(mola);
if (e.record.data.ESTLOT === '02') {
if (e.record.data.FECMOD === fecha_actual)
{
e.cancel = false; //permite
}
else{
e.cancel = true; //mo permite
}
} else
{
e.cancel = false; //permite
}
},
edit:
function editar(e, context, mola){
var record = context.record;
var recordData = record.getData();
var mola2= mola;
alert(mola2);
recordData.Funcionalidad = 'Modificar';
//alert(JSON.stringify(recordData));
Ext.Ajax.request({
url: 'http://localhost:8080/MyMaver/ServletTablaLotes',
method: 'POST',
// merge row data with other params
params: recordData
});
}
}
});

You are calling the function with
editar(mola);
But the function is defined as:
editar(e, context, mola)
So the function only receives the e parameter and the others are set to undefined.

the problem is not the mola variable but e.record. As your error message states the variable e either does not contain an object record or e.record is null. Try to console.log(e) to inspect your variable e further.

Related

How to expand Range of Array in Sheets based on column height

I have a custom formula that gets the redirect of a link. It takes an array as an argument. Its based on a Google script found here. https://developers.google.com/apps-script/guides/sheets/functions
The problem is that the source list gets updated and the range changes. If the range isn't exact, it breaks. Here is the code to the custom function:
function DOUBLE(input) {
return input.map(getRedirects);
}
function getRedirects(input) {
var urlKey = input;
var cache = CacheService.getScriptCache();
var result = cache.get(urlKey);
if (!result) {
var params = {
'followRedirects': false,
'muteHttpExceptions': true
};
var res = UrlFetchApp.fetch(input, params);
var finalURL = res.getHeaders()['Location'];
cache.put(urlKey, finalURL, 21600);
result = finalURL;
}
return result;
}
And here's the spreadsheet: working sheet
This should help you out. Wrap this in a try .. catch block. The UrlFetchApp fails when it gets an empty input. When this is the case the catch block kicks in. Other option is writing an if statement. if input is not '' then do the fetch and return, else.. ect.
function DOUBLE(input) {
return input.map(getRedirects);
}
function getRedirects(input) {
var params = {
'followRedirects': false,
'muteHttpExceptions': true
};
try {
var res = UrlFetchApp.fetch(input, params);
var finalURL = res.getHeaders()['Location'];
return finalURL
} catch(error){
return undefined
}
}
EDIT ("normal" function): (Why is my code block like that? I even tried to use a online beautifier...)
Select the range in your sheet
Custom menu "Redirects" -> Run
Output is placed in the column next to it.
function onOpen(e) {
SpreadsheetApp.getUi().createMenu('Redirects')
.addItem('run', 'getRedirects')
.addToUi()
}
function getRedirects() {
const activeRange = SpreadsheetApp.getActiveRange()
const values = activeRange.getValues().flat()
const output = []
const params = {
'followRedirects': false,
'muteHttpExceptions': true
};
values.forEach(url => {
try {
const res = UrlFetchApp.fetch(url, params);
const finalURL = res.getHeaders()['Location'];
output.push([finalURL])
} catch (error) {
output.push([JSON.stringify(error)])
}
});
activeRange.offset(0, 1).setValues(output)
}

Javascript--Breeze Manager Not Detecting Changes

I'm using the EntityManager from Breeze for the API portion of data-binding. However, the EntityManager fails to track the changes. It will execute the code like it's supposed to but it never recognizes the changes. What's the issue? Please, refrain from saying anything that is not constructive or any personal attacks. We're here as professionals and scientists(i know i am). Here is my code:
Service:
(function () {
var serviceId = 'UWRLService';
angular.module('myApp')
.factory(serviceId, ['$q', 'breeze', 'logger', 'appSettings', UWRLService]);
// console.log('Initialized UWRL Service.js');
function UWRLService($q, breeze, logger, appSettings) {
// console.log('inside datacontext -- UWRLService');
// configure logging for this service
logger = logger.forSource(serviceId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
//Setup variables with common Breeze query classes
var entityQuery = breeze.EntityQuery;
// setup breeze entity manager
var serviceName = appSettings.apiUrl + '/breeze/Uwrl/';//Where the entire service is pointing to
var manager = new breeze.EntityManager(serviceName);
var entityStateChangeAction = breeze.EntityAction.EntityStateChange;
// expose methods
var service = {
getChangesCount: getChangesCount,
saveChanges: saveChanges,
rejectChanges: rejectChanges,
getDivisions: getDivisions,
getPools: getPools,
getRandomCust: getRandomCust
//createChangeFactorEntity: createChangeFactorEntity,
};
return service;
// FUNCTION DECLARATIONS
//Attaches a new entity to the Breeze repository
//Passes the name and an array of values to seed the entity with
//function createChangeFactorEntity(entityName, initialValues) {
// var newFactor = manager.createEntity(entityName, initialValues);
// return newFactor;
//}
function getRandomCust()
{
var query = breeze.EntityQuery.from('alpha')
.where('customerNumber', '==', 1);
return executeQuery(query, 'Alpha found!');
}
function getDivisions()
{
var query = breeze.EntityQuery
.from('Divisions');
//executeQuery([query name], [query title])
return executeQuery(query, 'Divisions Found');
}
function getPools()
{
var query = breeze.EntityQuery
.from('Pools');
return executeQuery(query, 'Pools Found');
}
//Saves changes and logs exceptions
function saveChanges() {
var hasChanges = manager.hasChanges();
console.log(hasChanges);
console.log(manager.getChanges());
return manager.saveChanges()
.then(saveSucceeded)
.catch(saveFailed);
function saveSucceeded(saveResult) {
logSuccess("# of items saved = " + saveResult.entities.length, null, true);
logger.log(saveResult);
}
function saveFailed(error) {
var reason = error.message;
var detail = error.detail;
if (error.entityErrors) {
//Do nothing
} else if (detail && detail.ExceptionType &&
detail.ExceptionType.indexOf('OptimisticConcurrencyException') !== -1) {
// Concurrency error
reason =
"Another user, perhaps the server, " +
"may have deleted one or all of the todos." +
" You may have to restart the app.";
} else {
reason = "Failed to save changes: " + reason +
" You may have to restart the app.";
}
logError(reason, error, true);
throw error; //Downstream: users know it has failed
}
}
//Discards changes in Breeze Manager
function rejectChanges() {
if (manager.hasChanges()) {
count = getChangesCount();
manager.rejectChanges();
logWarning('Discarded ' + count + ' pending changes(s)', null, true);
}
}
//Returns (Nth-1) index of Breeze manager getChanges array
function getChangesCount() {
var ents = manager.getEntities();
var changes = manager.getChanges();
if (changes.length > 0)
{
alert("Changes made: " + manager.getChanges().length);
}
return manager.getChanges().length;
}
//Query Execution w/ toasters(logger)
function executeQuery(query, entityType) {
var promise = manager.executeQuery(query).then(querySucceeded, queryFailed);
return promise;
function querySucceeded(response) {
logSuccess(entityType + " query was successful", null, true);
return response.results;
}
function queryFailed(response) {
var message = response.message || entityType + " query failed";
logError(message, response, true);
throw error;
}
}
};
})()
Controller (javascript):
(function () {
'use strict';
var controllerId = 'UWRLController';
// console.log('Initialized UWRLController');
//Last item in passed array is the Controller (specific)
angular.module('myApp').controller(controllerId,
['$scope', 'UWRLService', 'logger',
'$routeParams', 'allStatesService', UWRLController]);
function UWRLController($scope, UWRLService, logger, $routeParams, allStatesService) {
// console.log('inside UWRLController');
//Loggin Initialization
logger = logger.forSource(controllerId);
var logError = logger.logError;
var logSuccess = logger.logSuccess;
var logWarning = logger.logWarning;
var uwrl = {};
$scope.uwrl = uwrl;
//Parameters we pass from Renewal Group Maintenance screen
//uwrl.PlanCode = $routeParams.PlanCode;
//uwrl.Contract = $routeParams.ContractNumber;
//uwrl.Mch = $routeParams.Mch;
//Functions in Javascript Controller
//[scope].[property] = [function name]
uwrl.saveChanges = save;
uwrl.discardChanges = discardChanges;
uwrl.changesCount = changesCount();
//uwrl.select = select;
init();//Initialize all customer related data for page
function init()
{
gettingDivisions();//Initialze getting data from Division's table through UWRL-service.js
getAllFiftyStates();
gettingPools();
gettingRandom();
}
function gettingRandom()
{
UWRLService.getRandomCust()
.then(function(alpha)
{
uwrl.alpha = alpha;
uwrl.beta = uwrl.alpha[0].customerName;
});
}
function gettingDivisions()
{
UWRLService.getDivisions()
.then(function (divisionNumber) {
uwrl.divisionNumber = divisionNumber;
});
}
function getAllFiftyStates()
{
allStatesService.getStates()
.then(function (allStates)
{
uwrl.allStates = allStates;
});
}
function gettingPools()
{
UWRLService.getPools()
.then(function (poolNumber)
{
uwrl.poolNumber = poolNumber;
});
}
//Clicking the Drop-down Button
//function select(change) {
// this.MchMcpPlanDesignId = change.MchMcpPlanDesign.MchMcpPlanDesignId;
// change.expanded = !change.expanded; //toggle back and forth
//}
////.then = [if] success
////.fail = failure
////.finally = always executed despite evaluated conditionals
//function getPlans() {//returns a promise
// uwrl.loadingPlans = true;
// UWRLService.getChangeFactors(uwrl.Mch, uwrl.Contract, uwrl.PlanCode)
// .then(function (deltaChangeFactor) {
// uwrl.deltaChangeFactor = deltaChangeFactor;
// }).finally(function () { uwrl.loadingPlans = false; });
//}
////Returns all data in ChangeFactorType table
//function getChangeFactorTypes() {
// UWRLService.getTypes().then(function (changeFactorTypes) {
// uwrl.changeFactorTypes = changeFactorTypes;
// });
//}
//Clicking on Save Button
function save() {
console.log('Save Button Clicked!');
//Validation -- checks for empty values
//if (uwrl.changeFactorType != null && uwrl.effectiveDate != null &&
// uwrl.changeFactorAmount != null) {
// //Adds a new Breeze Entity for ChangeFactor table in SQL database
// UWRLService.createChangeFactorEntity('ChangeFactor',
// {
// MchMcpPlanDesignId: this.MchMcpPlanDesignId,
// ChangeFactorType: uwrl.changeFactorType,
// EffectiveDate: uwrl.effectiveDate,
// ChangeFactorAmount: uwrl.changeFactorAmount
// });
//}
//Saves to Breeze Manager
//Must hit Art's ESB service -- to be researched
UWRLService.saveChanges();
}
//Gets rid of changes and logs it
function discardChanges() {
console.log('Discard Button Clicked!');
UWRLService.rejectChanges();
}
//Notifies user(s) of changes made that are
//either: savable, discardable
function changesCount() {
// console.log("Changes Made: " + UWRLService.getChangesCount)//for debugging purposes
return UWRLService.getChangesCount;
}
};
})();
The answer is to make sure to effect the model. For example: uwrl.alpha[0].customerName instead of urwl.beta

JavaScript if() case in CloudCode.

In this code im trying to get the Object for the caller of this method, using his unique username. If the object exists -> update it, of not -> create one.
However: my boolean value "found" is never changed. Even though, it must be changed after my Query. Because of this my if statement is never used and therefore no object created.
Does anyone know why?
To my knowledge its ok changing a global value from within a function.
Parse.Cloud.define("updateUserGeneral", function(request, response){
var UserGeneralObject = Parse.Object.extend("userGeneral");
var userGeneralNew = new UserGeneralObject();
var found = false;
var username = request.params.username;
var private_name = request.params.private_name;
var intentions = request.params.intentions;
var gender = request.params.gender;
var looking_gender = request.params.lookinggender;
var age = request.params.age;
var min_age = request.params.min_age;
var max_age = request.params.max_age;
var radius = request.params.radius;
var applyradius = request.params.applyradius;
var query2 = new Parse.Query("userGeneral");
query2.equalTo("username", username);
query2.first({
success: function(userGeneral){
if(userGeneral!=null){
found = true;
userGeneral.set("private_name", private_name);
userGeneral.set("intentions", intentions);
userGeneral.set("gender", gender);
userGeneral.set("lookinggender", looking_gender);
userGeneral.set("age", age);
userGeneral.set("max_age", max_age);
userGeneral.set("min_age", min_age);
userGeneral.set("radius", radius);
userGeneral.set("applyradius", applyradius );
userGeneral.save();
response.success("Succesfully saved userGeneral");
}else{
found = false;
}
},
error: function(error){
found = false;
}
});
if(found == false){
userGeneralNew.set("username", username);
userGeneralNew.set("private_name", private_name);
userGeneralNew.set("intentions", intentions);
userGeneralNew.set("gender", gender);
userGeneralNew.set("lookinggender", looking_gender);
userGeneralNew.set("age", age);
userGeneralNew.set("max_age", max_age);
userGeneralNew.set("min_age", min_age);
userGeneralNew.set("applyradius", applyradius);
userGeneralNew.set("radius", radius);
userGeneralNew.set("lookingForChat", 0);
userGeneralNew.set("lookingForInvitation", 1);
userGeneralNew.set("userHasChat", 0);
userGeneralNew.save(null, {
success: function () {
console.log("Save ok");
response.success("Succesfully saved userGeneral New");
},
error: function (error) {
console.log("Save failed");
response.error("Failed saving userGeneral New");
}
});
}
});
success: function(userGeneral){ is a callback function. In this case the code will most likely finish before you update the variable found. So the following code will run before the success function runs.
if(found == false){
userGeneralNew.set("username", username);
userGeneralNew.set("private_name", private_name);
userGeneralNew.set("intentions", intentions);
userGeneralNew.set("gender", gender);
userGeneralNew.set("lookinggender", looking_gender);
userGeneralNew.set("age", age);
userGeneralNew.set("max_age", max_age);
userGeneralNew.set("min_age", min_age);
userGeneralNew.set("applyradius", applyradius);
userGeneralNew.set("radius", radius);
userGeneralNew.set("lookingForChat", 0);
userGeneralNew.set("lookingForInvitation", 1);
userGeneralNew.set("userHasChat", 0);
userGeneralNew.save(null, {
success: function () {
console.log("Save ok");
response.success("Succesfully saved userGeneral New");
},
error: function (error) {
console.log("Save failed");
response.error("Failed saving userGeneral New");
}
});
}

Functions are undefined

I am trying to create a data management application, but instead of a Windows-based solution or using WebSQL, i am using IndexedDB. I am pretty new to it but I believe I have covered the basis in this draft of code.
Anyway, my problem is, anytime I run the code, my openDB() function and the addeventListener() function both run and show on the console log at runtime but all other functions are said to be undefined when I try to run the code. What could the problem be?
In the HTML file, the jQuery script file is referenced.
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
var DB_STORE_NAME = 'visitors';
var db;
var current_view_pub_key;
//opens the IndexedDB database
function openDb() {
console.log("open Database......");
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onsuccess = function (evt) {
db = this.result;
console.log("Database Opened");
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
console.log("Event fired when DB is needed to be upgraded");
var store = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('name', 'name', { unique: false });
store.createIndex('date', 'date', { unique: false });
store.createIndex('whom_to_see', 'whom_to_see', { unique: false });
store.createIndex('arrival_time', 'arrival_time', { unique: false });
store.createIndex('reason', 'reason', { unique: false });
store.createIndex('departure_time', 'departure_time', { unique: false });
};
}
//used to create a transaction
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
//adds a Visitor to the IndexedDB
function addVisitor(name, date, to_see, arrival_time, reason, departure_time) {
console.log("Adding the following data to IndexedDB: ", arguments);
var obj = { name: name, date: date, whom_to_see: to_see, arrival_time: arrival_time, reason: reason, departure_time: departure_time };
if(typeof blob != undefined)
{
obj.blob = blob;
}
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req;
try
{
req = store.add(obj);
}
catch(e)
{
if(e.name == 'DataCloneError')
displayActionFailure("This engine does not know how to clone a Blob, use Firefox!");
throw(e);
}
req.onsuccess = function (evt) {
console.log("Insertion into DB was successful. You can heave a huge sigh of relief!");
displayActionSuccess();
};
req.onerror = function () {
console.error("Insertion into DB failed!");
displayActionFailure(this.error);
};
}
function displayActionSuccess() {
alert("Whatever the heck you were doing was successful. Congrats!");
}
function displayActionFailure() {
alert("Oh Oh! System Failure! System Failure!");
}
// listens for the submit button event
function addEventListeners() {
console.log("Event Listeners");
$('#addVisitor').click(function(evt) {
console.log("Add Visitors Submit button");
var name = document.getElementsByName("txtName").value;
var date = document.getElementsByName("txtDate").value;
var whom_to_see = document.getElementsByName("txtToSee").value;
var time_of_arrival = document.getElementsByName("txtArrivalTime").value;
var reason_for_visit = document.getElementsByName("txtReason").value;
var time_of_departure = document.getElementsByName("timeOfDep");
addVisitor(name, date, whom_to_see, time_of_arrival, reason_for_visit, time_of_departure);
});
}
//makes the database open at runtime
openDb();
addEventListeners();
})
();
syntax error - you need a closing round bracket at end.
i.e add
);
I think the problem is the fact that when your anonymous function is run the browser doesn't not know about the '#addVisitor' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function () {
var DB_NAME = 'shodex';
var DB_VERSION = 1;
...
Instead of referencing the javascript code like before...
I removed all other functions from the javascript file leaving the openDB() function and placed them in the main html file. it worked automatically.

Ajax.Request of prototype framework hangs with multiple calls to jsp page

I have a problem concerning multiple ajax requests using prototype.js version 1.7.
Here is the function I wrote to make the ajax call:
function checkClonability(element) {
var strUrl = "/dssweb/js/ajaxdbdispatcher";
var rowIndex = element.id.split('_')[1];
var tabschema = $('tabschema_' + rowIndex).innerHTML.trim();
var tabname = $('tabname_' + rowIndex).innerHTML.trim();
var op = <%=AjaxDbDispatcher.CLONE_TABLE_COMPARE%>;
workLevel(rowIndex, 'run');
var qb = new QueryStringBuilder();
qb.addParameter('op', op);
qb.addParameter('dbsource', 'UAT');
qb.addParameter('dbtarget', 'PROD');
qb.addParameter('tabschema', tabschema);
qb.addParameter('tabname', tabname);
new Ajax.Request(strUrl, {
method:'post',
asynchronous: true,
parameters: qb.toString(),
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
if(json.equals) {
workLevel(rowIndex, 'ok');
element.onclick = '';
} else {
element.checked = false;
element.disabled = true;
workLevel(rowIndex, 'ko', 'La tabella ha un tracciato diverso in produzione!');
}
},
onFailure: function(err){
workLevel(rowIndex, 'none', 'Si è verificato un errore durante la verifica.');
}
});
}
The strUrl is a java servlet that makes a comparison of a database table between two different environments.
My page shows a list of tables and checkboxes to select them.
The function is fired by an onclick event on a checkbox. Everything works fine for a single call, but it hangs if I try to check several checkboxes without waiting for the end of the first call.
I tried it on chrome 8 and IE6 and I'm working on apache tomcat 6.
Any help would be apreciated.
when a user click two times quickly, the ajax request is send twice. Put some variable and a test on it that will stop a second execution if the ajax call hasnt ended:
var running = true;
function clickHandler() {
if (running) return;
running = true;
/** Some stuff here ***/
new Ajax.Request(strUrl, {
method:'post',
asynchronous: true,
parameters: qb.toString(),
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
if(json.equals) {
workLevel(rowIndex, 'ok');
element.onclick = '';
} else {
element.checked = false;
element.disabled = true;
workLevel(rowIndex, 'ko', 'La tabella ha un tracciato diverso in produzione!');
}
},
onFailure: function(err){
workLevel(rowIndex, 'none', 'Si è verificato un errore durante la verifica.');
},
onComplete: function() { running = false; }
});
}
NB: note sure about the onComplete callback, check the manuals to be sure running will be set false whenever the ajax call ends.
Ok, I think I've solved my problem with this 'workaround' class.
It syncronizes calls and make them sequential:
var Syncro = Class.create(
{
initialize: function(params) {
// Check for Prototype class
if(typeof Prototype=='undefined') {
throw("JSSyncro requires the Prototype JavaScript framework to run.");
}
//handle input parameters
this.delay = (typeof params.delay == 'undefined' ? 1000 : params.delay);
this.allowDuplicates = (
typeof params.allowDuplicates=='undefined' || typeof params.allowDuplicates!='boolean'
? true : params.allowDuplicates);
this.order = (
typeof params.order=='undefined' || ['fifo','lifo'].indexOf(params.order)==-1
? 'fifo' : params.order);
this.operations = [];
this.terminated = true;
// private - check for duplicate operations in the stack
this.alreadyExists = function(operation) {
var exists = false;
this.operations.each(
function(element) {
if(element.toString()==operation.toString()) {
exists = true;
return;
}
}
);
return exists;
};
//private - run operations sequentially
this.runSyncronized = function() {
function nextTimeout(instance) {
setTimeout(
function(){
instance.runSyncronized();
},
this.delay);
}
if(this.operations.length>0) {
if(this.terminated) {
this.terminated = false;
var cmd = (this.order=='fifo'
? this.operations.shift() : this.operations.pop());
cmd();
} else {
nextTimeout(this);
}
} else {
this.terminated = true;
}
};
},
// public - wakeup the executor and run the following operation if the previous is terminated
setTerminated: function(boolValue) {
this.terminated = boolValue;
},
// public - set the operation to execute sequentially
execute: function(operation) {
if(this.allowDuplicates || !this.alreadyExists(operation)) {
this.operations.push(operation);
this.runSyncronized();
}
}
}
);
Syncro class has two main methods:
execute - where you can pass the function you must execute inside an anonymous function
setTerminated - a setter method useful to set that an asyncronous operation has terminated (i.e. set in the onComplete method the async call done with ajax).
checkboxClick function is obviously called in the onclick event of my checkboxes.
Hope this could be useful.
Bye.
Just an evolution in the constructor.
Initial parameters (passed in the constructor) are defined in an array:
new Syncro({[delay:1000][, allowDuplicates:true|false][, order:'lifo'|'fifo']});

Categories

Resources