I am developing a "google maps API" based website, and I have a JSON file to parse. My code works fine on my laptop when I use chrome to test. Of course I used the "--allow-file-access-from-files" command to avoid the "same origin" protocol. However, the code don't work on my inMotion Hosting server. It yields a error:"marker feed error SyntaxError: Unexpected token o". Here is my code:
function loadJson() {
// JSON Parser
var feedSource = "json/markers07022014.json";
$.ajax({
url: feedSource,
success: function(data){
try{
//console.log("feed "+data);
//var jsonData = eval("(" + data + ")");
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.markers.length; i++) {
var output = [];
fireName[i]= jsonData.markers[i].name;
output["name"] = jsonData.markers[i].name;
output["summary"] = jsonData.markers[i].summary;
output["url"] = jsonData.markers[i].url;
output["lat"] = Math.round(jsonData.markers[i].lat*100)/100;
output["lng"] = Math.round(jsonData.markers[i].lng*100)/100;
output["contained"] = jsonData.markers[i].contained;
//todo new google.maps.LatLng(defLat, defLng)
//output["point"] = new GLatLng(parseFloat(jsonData.markers[i].lat), parseFloat(jsonData.markers[i].lng));
output["point"] = new google.maps.LatLng(parseFloat(jsonData.markers[i].lat), parseFloat(jsonData.markers[i].lng));
fireAddress[i]=output["point"];
// skip over incident details point for current incident
if (output["lat"] != detailLat || output["lng"] != detailLng) {
var marker = createMarker(output);
}
//if necessary createList of makers and windows if
}
} catch (anErr){
console.log("marker feed error "+anErr);
}
}
});
}
Related
I am trying to send email addresses from a google sheet to an external web page via Google Scripts, but it doesn't seem to be working.
From reading other similar issues it seems that I need the doPost() function but I'm unsure how I should incorporate it into my script.
Here's my google script
function getEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var myUrl = 'https://my.url/';
if(data) {
for(var i = 0; i < data.length; i++) {
if(i !== 0) {
postToForm(myUrl, data[i][0]);
}
}
deleteData(sheet, data);
}
}
function postToForm(url, data) {
UrlFetchApp.fetch(url + 'user/add/?email=' + data);
}
function deleteData(sheet, data){
for (var i = data.length; i>1; i--) {
sheet.deleteRow(i);
}
}
and here is the receiving script:
<script>
window.addEventListener('DOMContentLoaded', async () => {
if (location.search) {
const urlSearchParams = location.search;
try {
await DB.ready();
const email = getUrlParameter('email', urlSearchParams);
if (email) {
emailSignUp(email)
return;
}
} catch (error) {
console.log(error);
showSnackBar('Something went wrong', false);
return;
}
}
showSnackBar('Something went wrong', false);
});
function getUrlParameter(key, urlSearchParams) {
key = key.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + key + '=([^&#]*)');
var results = regex.exec(urlSearchParams);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
</script>
Maybe I need to change the postToForm function to doPost and add it that way?
Thanks
Answer
On one hand there is UrlFetchApp, it is designed to fetch resources and communicate with other hosts over the Internet. On the other hand there is, doPost that runs when an HTTP POST request is sent to a web app. It is developed by the user using Google Apps Script and publishing the script as web app.
In your case, as you are calling an external web, you need to use UrlFetchApp in a proper way. In the documentation there are two examples that show how to make the HTTP request, however your case looks different. Usually, when you make an HTTP POST request to send data to a server, you put that data on the message body request but depending on the design of your API, you can send data through the query component of the URI.
In your case, the code will look like this:
function postToForm(url, data) {
var uri = url + 'user/add/?email=' + data
var options = {
'method' : 'post',
'payload' : ''
};
UrlFetchApp.fetch(uri, options);
}
I'm trying to import data from a server, XML format via the server API, which require's a login.
Using information on this question: Cheers MogsDad
I can successful get the external xml file and data shows in the logger.
I cannot for the life of me write any of the info or elements to my spreadsheet. In the link shared, #mogsdad has linked to a parsing XML site. Unfortunately the link is dead. The current code returns an XML file. Normally I would try to use the importxml formula but not had much luck.
Have taken out my coding attempts to parse the XML so code doesn't look awful
has anyone got any pointers on how to parse some of all of the file or know a working URL for the XML parsing doc?
Here is my code so far. Thanks in advance
function importFromXml(){
var url = 'URL HERE'; // Advance search for macs not encrypted.
var username = 'USER HERE';
var password = 'PASSWORD HERE';
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
// Getting "bad request" here - check the username & password
var result = UrlFetchApp.fetch(url, options);
var state=result.getContentText();
// You should check state.getResponseCode()
Logger.log('1: '+state);
Logger.log(parse(state));
}
function parse(txt) {
var doc = Xml.parse(txt, true);
return doc; // Return results
}
**** EDIT ****
After a bit more playing, I have some progress.
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NoFirevault");
var range = ss.getRange(1, 1);
range.setValue(state);
I managed to write the XML contents to my sheet. Albeit in one cell. When I try to split the data into cells, using the data length and use setValues. It bums out on me, will keep on playing.
**** EDIT *****
After a bit more playing around. I can get XML data written to sheet.
There's 31 entries, with various attributes. But these all get written to a single cell per entry.
Which is an improvement on ALL 31 entries going to a single cell.
In case it helps, here is the XML layout I'm looking at.
I want the computer data, in the computers section.
function importFromJamf(){
var url = 'URL HERE'; // Advance search for macs not encrypted.
var username = 'USER HERE';
var password = 'Password';
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
var result = UrlFetchApp.fetch(url, options);
var state = result.getContentText();
var document = XmlService.parse(state);
var entries = document.getRootElement().getChild('computers').getChildren(); // Working but values joined into one row
for (i=0;i<entries.length;i++){
var value = entries[i].getValue();
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange(i+1,1).setValue(value);
}
}
function importFromJamf(){
var url = 'url';
var username = 'user';
var password = 'pw';
var headers =
{
Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
}
var options =
{
"method" : "get",
"headers": headers
};
var result = UrlFetchApp.fetch(url, options);
var state = result.getContentText();
var document = XmlService.parse(state);
var array= [];
var entries = document.getRootElement().getChild('computers').getChildren('computer');
for(i = 0 ; i < entries.length ; i++){
var a = entries[i].getContent(5).getValue();
var b = entries[i].getContent(8).getValue();
var c = entries[i].getContent(9).getValue();
var d = entries[i].getContent(6).getValue();
var e = entries[i].getContent(11).getValue();
var f = entries[i].getContent(12).getValue();
var g = entries[i].getContent(10).getValue();
var data = [a,b, c,d,e, f,g];
array.push(data);
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange("A2:Z").clearContent();
var range = sheet.getRange(2,1,array.length, array[0].length);
range.setValues(array);
}
Code above works for what I need, it allows me to grab the values I want into an array I can use to write to a sheet.
.getContent() helped me get the values of y columns of array each loop
But I'm sure there are better ways of going about it.
I am a newbie in coding.
I am trying to create a function in google app script that acts like a dictionary and pulls out the meaning of the word passed as the argument. Its using the API of oxford dictionaries but its not working. Its showing the error 403. "var response = UrlFetchApp.fetch(url,headers);" shows the error.
function Word_meaning(word){
var url="https://odapi.oxforddictionaries.com:443/api/v1/entries/en/" + word + "/regions=us";
var headers =
{
'Accept': 'application/json',
'app_id': 'abc',
'app_key': '123'
};
var response = UrlFetchApp.fetch(url,headers);
var data = JSON.parse(response.getContentText());
Logger.log(data);
}
A couple of things - why do you include the port number in the API call? My API endpoint for querying Oxford Dictionaries looks different. Also, there's a dash in "od-api".
https://od-api.oxforddictionaries.com/api/v1/entries/en/{word_id}/regions={region}
Testing the link in the address bar, I get the expected server response of "Authorization required" while the URL you provided doesn't seem to exist.
Anyway, the error pops up because the optional 'params' object for the UrlFetchApp.fetch(url, params) method is not constructed properly. The "headers" property must be contained within that object. Somewhat ambiguous here, but please read:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)
I was able to get things up and running using the code below.
function getData(word, region){
var word = word || "leprechaun";
var region = region || "us";
var wordId = encodeURI(word);
var baseUrl = "https://od-api.oxforddictionaries.com/api/v1/entries/en/{word_id}/regions={region}";
var app_id = "app_id";
var app_key = "app_key";
var headers = {
"app_id": app_id,
"app_key": app_key
};
var options = {
"headers": headers,
"muteHttpExceptions": true
};
var url = baseUrl.replace("{word_id}", wordId)
.replace("{region}", region);
var res = UrlFetchApp.fetch(url, options);
var responseCode = res.getResponseCode();
if (responseCode == 200) {
var data = JSON.parse(res.getContentText());
} else {
Logger.log(res.getContentText());
}
}
I'm using Parse.com give people an ability to share a URL from the app, to an individual "object" in Parse.com.
The below code works fine- EXCEPT for some reason the "LINK" (URL) is not coming through. All the other data comes through.
Is there a trick with Parse and sharing URL's?
My HTML is fine, I"ve pasted my javascript below.
var url = document.URL;
var objectId = url.substr(url.lastIndexOf('/') + 1);
var name;
var designer;
var itemDescription;
var price;
var link;
var image;
Parse.initialize("xxx", "xxx");
var garmentsAPI = Parse.Object.extend("garmentsAPI");
var query = new Parse.Query(garmentsAPI);
query.get(objectId, {
success: function(garments) {
console.log("success");
name = garments.get("name");
designer = garments.get("designer");
itemDescription = garments.get("itemDescription");
price = garments.get("price");
link = garments.get("link");
image = garments.get("smallImage1");
$("#designer").html(designer);
$("#name").html(name);
$("#itemDescription").html(itemDescription);
$("#price").html(price);
$("#image").attr("src", image.url());
$("#buyButton").attr('href', link);
console.log(image.url());
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
console.log("fail");
}
});
if your column name of file is
smallImage1 then
you can get url of file is as follows:
smallImage1._url
Have tried many options to update a product in ECWID using Google Apps Script UrlFetchApp.fetch() put method but not succeeded. Following are the different ways that I've written the code and tested, but am getting different type of errors.
I guess, am missing some small thing, which am not able to figure it out. Please help me to fix this issue.
API: ECWID Products API (http://kb.ecwid.com/w/page/25285101/Product%20API#RESTAPIMethodupdateaproduct)
Method: PUT (to update the product details)
Sample Code 1:-
function updateProducts(){
var products_authkey = "xxxxxxxx";
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var options ={method:"put",ContentType:"application/json",payload:payload};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 2:-
Tried converting the object to json stringify, but the same error.
function updateProducts_version2(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = Utilities.jsonStringify(payload);
var options ={method:"put",ContentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
"{ "error": "OTHER", "errorMessage": "Error parsing JSON: A JSONObject text must begin with '{' at character 0" }"
Version 3:- (Tried passing secure_auth_key using Authorization in headers)
function updateProducts_version3(){
try{
var url ="https://app.ecwid.com/api/v1/xxxxx/product?id=xxxxx";
var payload = {price:62755};
var headers = {Authorization: 'xxxxxxx'};
var options = {headers:headers,method:"put",ContentType:"application/json",payload:payload};
var options ={method:"put",ContentType:"application/json",payload:payload,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
Error:-
{ "error": "OTHER", "errorMessage": "API key not found in request parameters" }
Also to note that, I've tried using DevHttpClient chrome plugin, it's updating properly.
Which means that there's some problem the way we're using UrlFetch. Please help me in fixing this issue...
Thanks in advance...
Credentials are needed to test this, so that's up to you. You probably need to both stringify & encode the payload. You also had incorrect capitalization on contentType, which you could check with UrlFetchApp.getRequest().
function updateProducts_version2a(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product?id=xxxxx&secure_auth_key="+products_authkey;
var payload = {price:62755};
var payload_json = encodeURIComponent(JSON.stringify(payload));
var options ={method:"put",contentType:"application/json",payload:payload_json,muteHttpExceptions:true};
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var x = 1;
}catch(e){
Browser.msgBox(e);
}
}
This next version seemed to work - by suppressing the price change and using a store's ID, it mimicked a product 'get', according to the docs you referenced. This time, the error message might be indicating some level of success: "This Ecwid account doesn't have access to Ecwid API. Please, consider upgrading it."
You'll notice that the URL has been separated out, with the basic header info of product ID and auth key together.
function updateProducts_version4(){
try{
var url ="https://app.ecwid.com/api/v1/xxxx/product";
var payload = encodeURIComponent(JSON.stringify({
price:62755
}));
var headers = {id:'xxxx',
secure_auth_key: 'xxxxxxx'
};
var options = {
headers:headers,
method:"put",
contentType:"application/json",
muteHttpExceptions:true,
payload:payload
};
var request = UrlFetchApp.getRequest(url, options); // Debug: check what would be fetched
var result = UrlFetchApp.fetch(url, options);
var response = result.getContentText();
var res_code = result.getResponseCode();
var respHeaders = result.getHeaders(); ///
debugger;
}catch(e){
Logger.log(e);
//Browser.msgBox(e);
}
}
Without your creds, that's as far as I can take it... tell us how that works for you.