Javascript API - Error 401 - Missing api_id when clicking on SearchBox - javascript

I have two symptoms that make me think there's something wrong with my Nokia appId/token. One is that when I try to use the searchbox, I get a javascript error "Error 401 - Missing api_id". The second is when I go to developer.here.com and to My Apps, and look at the hit history of my app, I see zero hits. What am I doing wrong?
nokia.Settings.set("appId", "[My ID]");
nokia.Settings.set("authenticationToken", "[MY TOKEN]");
var my_lat = 41.88
var my_lon = -87.63
map = new nokia.maps.map.Display(document.getElementById('mapcanvas'), {
'components': [
// Behavior collection
new nokia.maps.map.component.Behavior(),
new nokia.maps.map.component.ZoomBar(),
new nokia.maps.map.component.Overview(),
new nokia.maps.map.component.TypeSelector(),
new nokia.maps.map.component.ScaleBar()
],
'zoomLevel': 11, // Zoom level for the map
'center': [my_lat, my_lon] // Center coordinates
});
// Initialize search box:
var searchBox = new nokia.places.widgets.SearchBox ({
targetNode: 'searchbox',
searchCenter: function () {
return {
latitude: my_lat,
longitude: my_lon
}
},
onResults: function (data) {
renderResults (data);
}
});
// Handle the results of the search. This callback function
// receives the raw places data as an array. For each element
// in this array, it creates an HTML list element and fills
// it with the name of the place:
function renderResults (data) {
var previewList = document.getElementById ('results');
previewList.innerHTML = '';
var results = data.results.items;
for (var i = 0, l = results.length; i < l; i++) {
var result = results[i];
var resultLi = document.createElement ('li');
resultLi.innerHTML = result.title;
previewList.appendChild (resultLi);
}
}

The problem was how I was getting the javascript lib.
This is what worked. Note the "with=maps,places".
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=maps,places"></script>
Here's what did not work
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js"></script>
<script type="text/javascript" src="http://api.maps.nokia.com/2.2.4/jsl.js?with=places"></script>

Your code looks correct - my assumption would be that the appId and token you are using are not valid.
Firstly to prove this is the case start with the code behind the Places Widget example. Copy the code to your PC or local server and see if you can get a local copy working for you - if you type the word Airport into the search box you should get suggestions appearing after the first three letters, and markers on the map once you click search.
Now try replacing the app id and token wih blanks:
nokia.Settings.set("appId", "");
nokia.Settings.set("authenticationToken", "");
The application should no longer work. If this is also the case when you enter your appId and token then it looks like you have incorrectly copied them, used the app name by mistake (or something is up with the back-end).
The most comprehensive guide to creating a new appId and token can be found here - I would follow it from scratch and create a new one if necessary. When logged in and you click on Manage Apps the appId and token can be found in the boxes on the right. Double click on the box to select all and ensure that you don't inadvertently miss the final character which may not quite fit in the box.
Go back to your working demo example and replace the demo appId and token with the ones associated with your account. Hopefully it should now work for you.

Related

Suitescript: Can't Get Result From Search

The following is the script that I write for writing back "ship from location" information to Item Fulfillment for a certain customer. But it's not working.
Anyone see a syntax error, know what I might be missing, or what I can test for?
case "2946":
var warehousecode = WH_Code_Lookup(customer , location);
itemfulfillment.setFieldValue('custbody_warehouse_code', warehousecode);// set warehouse code
// Set Ship from location
var columns = [];
columns[0] = new nlobjSearchColumn('address1');
columns[1] = new nlobjSearchColumn('address2');
columns[2] = new nlobjSearchColumn('city');
columns[3] = new nlobjSearchColumn('state');
columns[4] = new nlobjSearchColumn('country');
columns[5] = new nlobjSearchColumn('zip');
var search = nlapiSearchRecord('location', null, new nlobjSearchFilter('internalid', null, 'is', invCheckFlag), columns);
itemfulfillment.setFieldValue('custbodyship_from_address1', search[0].getValue('address1'));
itemfulfillment.setFieldValue('custbodyship_from_address2', search[0].getValue('address2'));
itemfulfillment.setFieldValue('custbodyship_from_city', search[0].getValue('city'));
itemfulfillment.setFieldValue('custbodyship_from_country', search[0].getValue('country'));
itemfulfillment.setFieldValue('custbodyship_from_state', search[0].getValue('state'));
itemfulfillment.setFieldValue('custbodyship_from_postal_code', search[0].getValue('zip'));
if(location == 6){
itemfulfillment.setFieldValue('thirdpartyacctups',edi_customer_search[0].getValue('custrecord_2nd_3rd_pty_ups'));
itemfulfillment.setFieldValue('thirdpartyzipcodeups',edi_customer_search[0].getValue('custrecord_2nd_3rd_pty_ups_zip'));
itemfulfillment.setFieldValue('thirdpartytypeups','BILLTHIRDPARTY');
}
break;
You stated that the code doesn't work. Is there a specific error, as someone asked? Does the search bring back results or is it an issue in the search itself? Did you add any debug code in your script to see if you can pinpoint where the issue may be?

Remove Duplicate Items From Multidimensional Array Using Javascript, jQuery, & underscore.js

I have a web page which uses jQuery to fetch data from a JSON file that contains a location name, latitude, and longitude. I then push the retrieved data into an array.
var weatherSites = [];
function weather() {
$.getJSON('json/LOCS.json', function(data) {
$.each(data.locations, function() {
var locationLatitude = this.latitude;
var locationLongitude = this.longitude;
var locationName = this.location;
// -- If the latitude and longitude are 0,0 then skip to the next iteration --
if (locationtLatitude == +0 || locationLatitude == -0 && locationLongitude == +0 || locationLongitude == -0) {
return true;
}
// Populate array with site name, latitude, and longitude
weatherSites.push({name: locationName, latitude: locationLatitude, longitude: locationLongitude});
});
});
};
The code retrieves the data and populates the array as required. However, there are a number of locationName items which are the same, even though the locationLatitude and/or locationLongitude are different. I need to remove from the array elements where the locationNames are the same, regardless of the latitude or longitude.
I have tried using a number of methods seen here but have had no luck. For example:
function removeDupes() {
var uniques = _.map(_.groupBy(weatherSites,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
This example requires underscore.js. This did not work for me. I am new to programming and GIS in general. I would appreciate an answer which contains the full code necessary and hopefully the logic behind what is happening. This would be very helpful for me and will of course help me to learn.
Thank you for your help.
The open source project http://www.jinqJs.com can easily do it.
Here is the GitHub link: GitHub
var results = jinqJs()
.from(data1)
.groupBy('locationName')
.max('locationLatitude', 'locationLongitude')
.select();
Let me know if you need any working examples.

"The property or field 'Id' has not been initialized. It has not been requested..." when trying to access GUID of Library in SharePoint via JavaScript

I am trying to access the ID of Library using client-side object model in SharePoint 2013. But I am getting error as:
The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Below is my code:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var items = SP.ListOperation.Selection.getSelectedItems(context);
var currentLibrary = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList(context));
context.load(currentLibrary, 'id'); // Tried with 'Id' but still throws error
console.log(currentLibrary);
console.log("currentLibrary.get_id = " + currentLibrary.get_id()); // THROWS ERROR!
What am I doing wrong here?
The error:
The property or field 'Id' has not been initialized. It has not been
requested…
occurs since List object has not been requested.
Use SP.ClientContext.executeQueryAsync method to execute the current pending request asynchronously on the server
A working example:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var listId = SP.ListOperation.Selection.getSelectedList(context);
var list = web.get_lists().getById(listId);
context.load(list, 'Id'); //tell SharePoint to load List Id property
context.executeQueryAsync( //submit query to the server
function(){
console.log("ID:" + list.get_id()); //process result in success callback
},
function(sender,args){
console.log(args.get_message()); //handle error in error callback
}
);
my issue happened to be a silly one, the column I was returning was originally created with the name Requestor_DisplayName, and later changed to Employee_DisplayName so when using:
oListItem.get_item('Employee_DisplayName');
I got the >
"The property or field 'Id' has not been initialized. It has not been requested…" error
The issue had nothing to do with the SP.ClientContext.executeQueryAsync method itself...
When I changed the code to:
oListItem.get_item('Requestor_DisplayName');
It ran with out issue. You can use SP CAML Query Helper Online to inspect your your list and columns (as well as build CAML Queries) this is how I discovered my issue:
Hope this helps someone in the future!
Thanks.
SG.
Well back again editing this answer as today made another discovery about this error message similar in concept, I did not realize SharePoint will trim your column names after 32 Characters in length...
I got the exact same error message as before in the Developers Tool > debug console (IE f12) but about a different column of course.
"The property or field 'Operations_Approver1_Display_Name' has not been initialized. It has not been requested…"
I was left scratching my head after checking column names in list settings as I had in my JSOM, the column name was "Operations_Approver1_Display_Name" (Yes I was once a COBOL developer so I like long and Meaningful Names LOL)
oListItem.get_item('Operations_Approver1_Display_Name');
All seemed to check out, I thought "Well maybe I have a type in original column name and don't remeber fixing it" So of course I naturally opened up, SP CAML Query Helper Online (man I lobe this tool, yes the b was on purpose LOL).
This is how I discovered that SharePoint has a limit of 32 Characters for column names, just wanted to update this answer since it is highly ranked on search. As you can see in the screenshot below that the InternalName name of the column has been cut short by one character from its "Title" column name (Leave it to me to make this Name 33 characters long just 1 over the limit)
using Vadim answer:
var oItem ='';
function retrieveWebSite() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var clientContext = new SP.ClientContext.get_current();
this.oWebsite = clientContext.get_web();
clientContext.load(this.oWebsite);
var lstObject = oWebsite.get_lists().getByTitle('Listname');
oItem = lstObject.getItemById(5);
clientContext.load(oItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
});
}
function onQuerySucceeded(sender, args) {
var look = oItem.get_item('LookupColumnName').get_lookupValue();
var title = oItem.get_item('Title');
var id = oItem.get_id();
alert("Loook up column value: "+look);
alert("Title column: "+title);
alert("Id column value: "+id);
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
you are looking for ids then do like this:-
var context = SP.ClientContext.get_current();
var web = context.get_web();
var items = SP.ListOperation.Selection.getSelectedItems(context);
for (var i = 0; i < items.length; i++) {
var id= items[i].id;
}
Thanks :)

doPost "unexpected error encountered" Web Form when submitting

I'm stuck on this web form after submitting. The below code worked in a previous web form I created with the help of Serge and a few others here some time ago. I'm attempting to re-purpose the code to make a PTO request web form. Right now, when submitting it spits out a "unexpected error encountered error and I'm lost on attempting to locate the issue. I'm thinking it may be how I've added panels together and their relationship? This is a work in progress, so i know clickhandlers will be added to provide response after submit etc. At the moment I'm looking to make sure it's passing entries in form to the spreadsheet. Thanks for any assistance.
//Setting the spreadshet ID and style of the form
var submissionSSkey = 'PUT YOUR KEY HERE'
var PanelStyle = {'background':'#c0d6e4','padding':'40px','borderStyle':'ridge','borderWidth':'15PX','borderColor':'#31698a'}
// Script-as-app template.
function doGet(e) {
//Creating the Appplication
var app = UiApp.createApplication();
//Creating panels to house the web form, instructional text, data pickers and setting style
var vertPanel = app.createVerticalPanel().setTitle('XYX Company PTO Request Form').setStyleAttributes(PanelStyle).setPixelSize(350,250);
var mainPanel = app.createFormPanel().setPixelSize(350,150);
var grid = app.createGrid(4,4).setId('ptogrid');
var ptoStart = app.createDateBox().setWidth('200').setName('ptoStartDate');
var ptoEnd = app.createDateBox().setWidth('200').setName('ptoEndDate');
var submitButton = app.createSubmitButton('<B>Submit</B>');
//Assigning widgets to the grid for positioning
grid.setText(1, 0, 'PTO Start Date')
.setWidget(1, 1, ptoStart)
.setText(2, 0, "PTO End Date")
.setWidget(2, 1, ptoEnd)
.setText(3, 0, '')
.setWidget(3, 1, submitButton)
//Instructions for completion of the PTO form by users.
vertPanel.add(app.createHTML("<b>PTO Request Form</b>"));
vertPanel.add(mainPanel);
vertPanel.add(app.createHTML("<br><b>Instructions:</b></br>" +
"<p>Select the starting date and the ending date for your PTO request. "+
"If you are taking a single day of PTO enter the starting and ending date as the same date. "+
"Click Submit once you've enter the dates. A request will be sent to your manager for reivew / approval.</p>"));
//Grabbing active users session information in order to look up user group assignment and manager
var employee = Session.getActiveUser().getEmail();
//Uses the UserManager class to get info by passing in the getActive user from base class
var userFirst = UserManager.getUser(Session.getActiveUser()).getGivenName();
var userLast = UserManager.getUser(Session.getActiveUser()).getFamilyName();
var wholeName = userFirst +" "+ userLast;
mainPanel.add(grid);
app.add(vertPanel);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var ptoStart = e.parameter.ptoStartDate;
var ptoEnd = e.parameter.ptoEndDate;
//var wholeName = e.parameter;
var timeStamp = new Date();
//Access spreadsheet store values
var sheet = SpreadsheetApp.openById(submissionSSkey).getSheetByName('PTO Requests');
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 11).setValues([[timeStamp,ptoStart,ptoEnd]]);
app.close();
return app;
}
I'm pretty sure the error comes from the spreadsheet ID, the sheet name or the range definition, please double check these parameters and see if it solves the issue.
I checked on my account with wrong values and it generated the same issue you have, it works as expected with correct values.
Edit: your comment seems to confirm that...( didn't see it when I answered...)
Note: the error was easy to find by looking at the execution transcript in the script editor UI, it would even give you the line of code where the error occured.

javascript arrays on gmaps

i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html

Categories

Resources