uilocations is declared but its value is never read - javascript

I'm building a price prediction model using Python, Flask Server, HTML, and CSS. I've implemented the HTML and CSS code but I'm having issues getting my dropdown button to read all my locations via a JavaScript call (all the locations are saved in a json file). Concerning 'uilocations' it keeps showing 'uilocations is declared but its value is never read. Below is my javascript code:
function onClickedEstimatedPrice(){
var uiBathrooms = document.getElementsByName("uiBathrooms");
for(var i in uiBathrooms) {
if(uiBathrooms[i].checked) {
return parseInt(i)+1;
}
}
return -1;
}
function getBHKValue() {
var uiBHK = document.getElementsByName("uiBHK");
for(var i in uiBHK) {
if(uiBHK[i].checked) {
return parseInt(i)+1;
}
}
return -1; // The above functions iterate through the buttons and return the values
}
function onClickedEstimatedPrice() {
console.log("Estimated price button clicked");
var sqft = document.getElementById("uilocations");
var bathrooms = document.getElemenbtById("uiEstimatedPrice");
var estPrice = document.getElementById("uiEstimatedPrice")
var url = "http://127.0.0.1:5000/predict_home_price"; //url for the price prediction endpoint
$.post(url, { //This is a jquery POST call that makes a POST call to the url, we will get our output back in 'data'
total_sqft: parseFloat(sqft.value),
bhk: bhk,
bath: bathrooms,
location: location.value
},function(data, status) {
console.log(data.estimated_price);
estPrice.innerHTML = "<h2>" + data.estimated_price.toString() + " Lakh</h2>";
console.log(status)
}
)
}
function onPageLoad() {
console.log( "document loaded" );
var url = "http://127.0.0.1:5000/get_location_names"; //Here we make our HTTP Call
$.get(url,function(data, status) { //This is a jquery GET call that makes a GET call to the url, we will get our response back in the 'data'
console.log("got response for get_location_names request");
if(data) {
var locations = data.locations; //This will be our list of locations
var uilocations = document.getElementById("uilocations");
$("#uilocations").empty();
for(var i in locations) {
var opt = new Option(locations[i]);
$("#uilocations").append(opt);
} //The above goes through our locations one by one and adds them to our dropdown
}
});
}
window.onload = onPageLoad; //This will be used to load our HTML page and load the locations
I tried the code above, i expected my dropdown button to pick more locations but whenever i refresh the page on my browser, i don't get the expected output

Related

Can't get data out of indexedDB

Here's the function I'm trying to call:
function restoreCurrent() {
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2);
tzact.onerror = function(event) {
alert ("Failed to retrieve the data.");
}
tzact.onsuccess = function(event) {
document.getElementById("demo").innerHTML += "Transaction success.<br />";
}
}
window.onload = function() {
restoreCurrent();
}
As you can see, it should output something on either a success or an error. In fact it doesn't output anything. I had further code after this in the .onsuccess function, but nothing gets executed. And the line where it stops working is the database call, I've tested that much.
For the record, both this line of code when I created the database
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").add({id : 2, pictureData : working});
and this line when I try and update that particular record
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").put({id : 2, pictureData : working});
seemed to execute OK -- or at least, the functions they were embedded in went on to output success messages. Without being able to extract any data it's hard to be sure.
EDIT: Figured it out myself. The answer is that I had to put this into each function:
var request = window.indexedDB.open("[database name]",5);
request.onerror = function() {
alert ("Failed to open the database.");
}
request.onsuccess = function() {
var db = request.result;
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2); // or "readwrite" and .put(2), as the case might be
tzact.onerror=function() {
alert ("Data transaction failed.");
}
tzact.onsuccess=function() {
document.getElementById("demo").innerHTML += "Data transaction successful.<br />";
if (tzact.result) {
var working = tzact.result.pictureData;
// the rest of the function goes here
} else {
alert ("No data received.");
}
}
}

ServiceNow auto-populate Script not being called

I have a table in ServiceNow that contains Store and a corresponding Tier that is associated with the Store.
I am trying to auto-populate a record producer, once Store is selected. and my script is not running.
The table is a custom table created in a scoped application which is new to me so not sure what I am doing wrong in the scripting. Any advice?
//Catalog Client Script (runs on [Store] Record Producer Change)
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// new GlideAjax object referencing store of AJAX script include
var ga = new GlideAjax("HRProfileAjax");
// add store parameter to define which function we want to call
// method store in script include will be getFavorites
ga.addParam("sysparm_store", "getHRProfile");
ga.addParam("sysparm_tier", "getHRProfile");
// submit request to server, call ajaxResponse function with server response
ga.getXML(ajaxResponse);
function ajaxResponse(serverResponse) {
// get result element and attributes
var result = serverResponse.responseXML.getElementsByTagstore("result");
var message = result[0].getAttribute("tier");
//check for message attribute and alert user
//if(message)
//alert(message);
//build output to display on client for testing
// get favorite elements
var favorites = serverResponse.responseXML.getElementsByTagstore("favorite");
for(var i = 0; i < favorites.length; i++) {
var store = favorites[i].getAttribute("store");
g_form.setValue(store);
var tier = favorites[i].getAttribute("tier");
//output += store + " = " + tier + "\n";
g_form.setValue(store,tier);
}
//g_form.setValue('number',output);
}
//Script #2 HR PROFILE AJAX
/*
* HRProfileAjax script include Description - sample AJAX processor returning multiple value pairs
*/
var HRProfileAjax = Class.create();
HRProfileAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
/*
* method available to client scripts call using:
* var gajax = new GlideAjax("HRProfileAjax");
* gajax.addParam("sysparm_store", "getFavorites");
*/
getHRProfile : function() {
// build new response xml element for result
var result = this.newItem("result");
var store = this.getParameter('store');
var hrPro = new GlideRecord('x_hiring_gri_hr_storetier');
hrPro.addQuery('store',store);
hrPro.query();
if(hrPro.next()){
result.setAttribute("message", "returning all favorites");
this._addFavorite("tier", hrPro.tier);
}
},
_addFavorite : function(store, value) {
var favs = this.newItem("favorite");
favs.setAttribute("store", store);
},
type : "HRProfileAjax"
});

Return string from second function

Well i have created a function to return the picture url. See code below:
function loadAttachment(itemid) {
web = context.get_web();
attachmentFolder = web.getFolderByServerRelativeUrl("Lists/LijstMedewerkers/Attachments/" + itemid);
attachmentFiles = attachmentFolder.get_files();
//Load attachments
context.load(attachmentFiles);
context.executeQueryAsync(onLoaddAttachmentSuccess, onLoadAttachmentFail);
alert(picture);
return picture;
}
function onLoadAttachmentFail(sender, args) {
alert('Failed to get lists items. Error:' + args.get_message());
}
function onLoaddAttachmentSuccess(sender, args) {
// Enumerate and list the Asset Attachments if they exist
var attachementEnumerator = attachmentFiles.getEnumerator();
while (attachementEnumerator.moveNext()) {
var attachment = attachementEnumerator.get_current();
picture = attachment.get_serverRelativeUrl();
}
}
Well it's not returning the value of the picture. When i do an alert i see the value but with the return it's not working. even if i put the picture in the itemid.
Any idea what i'm doing wrong ?
Since SP.ClientContext.executeQueryAsync method is async:
SP.ClientContext.executeQueryAsync(succeededCallback, failedCallback)
succeededCallback is used for declaring function that contains the returned results.
When working with asynchronous API such as JSOM the following patterns are commonly used:
Using nested callbacks
Using the promises pattern
The below example demonstrates how to retrieve attachment files using callback approach:
function loadAttachments(listTitle, itemId,success,error) {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var listItem = list.getItemById(itemId);
var files = listItem.get_attachmentFiles();
context.load(files);
context.executeQueryAsync(function(){
success(files);
},
error);
}
Usage
Get first file attachment url
loadAttachments('Projects',3,
function(attachmentFiles){
if(attachmentFiles.get_count() > 0) {
var attachmentFile = attachmentFiles.getItemAtIndex(0);
var fileUrl = attachmentFile.get_serverRelativeUrl();
//...
}
},
function(sender,args){
console.log(args.get_message());
});

Removing Javascript alert line stops my append code working correctly

So, I've got the below code: -
function testing(results) {
$table = $('#formList')
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
}
It basically takes a JSON file and then adds the data into the right sub tables within a main table via appends etc.
The oddity is during debug I had an alert in there to check the html of the table it was identifying (making sure it had found the right sub table etc) and all worked well. But if I remove that alert it then suddenly only appends all the data to the last sub table in the main table?! Any clues?
It's a classic JavaScript closure-loop problem. The variables defined in the for loop are being reassigned each time within the loop and responses from the AJAX requests(which are async) get appended to the last sub-table. It works when you have an alert because the variables have not been reassigned(as alert blocks the for loop execution) by the time AJAX request is completed.
You could handle this by having a function do the AJAX request and append. The variables are not reassigned within this function and hence should work.
function testing(results) {
$table = $('#formList')
function appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal){
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal);
}
}
Without seeing more of your code, I can't say for sure. But when I had a similar issue it was because I was using append outside of my $(document).ready(function(){ /*stuff here*/ })
Essentially the object I was appending to hadn't loaded yet.
in your Ajax call use its argument 'async';
it accepts Boolean value, pass the value 'false' in it.
Try it
Move
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
To your callback function:
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data);
}).done(function(){});

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources