I'm trying to use an API which returns me a JSON so I can use it on my function.
Imports
I'm importing Jquery, instafeed.min.js and the API (instant-tokens.com).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/instafeed.js/1.3.2/instafeed.min.js"
integrity="sha512-CoWJ3qoyvZZrGHIctI7xjuAyhg2MCZfBZ8P7PjOBA+Xp2N/xl6YUxxmE+aV4w0056tfemwyseDhf2nXlEgAF2A=="
crossorigin="anonymous"></script>
// this one is in the head section
<script src="https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token.js?userSecret=slqh9w7letquro8mj056yi"></script>
Instafeed script
<script type="text/javascript">
$(document).ready(function () {
var instantTokenApiUrl = 'https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token.js?userSecret=slqh9w7letquro8mj056yi'
$.ajax({
url: instantTokenApiUrl,
dataType: 'json',
})
.done(function (response) {
if (!response.Token) {
console.log('Error :: ', response);
} else {
var feed = new Instafeed({
accessToken: response.Token
});
feed.run();
}
});
});
</script>
I'm trying to do what's in this post: https://github.com/codingbadger/instant-tokens.com/wiki/3.-Instafeed.js-Demo
But my feed still isn't displaying, and it gives me these CORS errors:
Access to XMLHttpRequest at 'https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token.js?userSecret=slqh9w7letquro8mj056yi' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token.js?userSecret=slqh9w7letquro8mj056yi net::ERR_FAILED
jquery.min.js:2 XHR failed loading: GET "https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token.js?userSecret=slqh9w7letquro8mj056yi".
My question is: Is there a workaround for this? I'm fairly new to ajax and JSON, so I hope people can tell me what I'm doing wrong.
Update
For some reason, it worked after I added the instafeed function manually to my code, instead of linking it from an external source.
And at the end, I'm making an ajax request.
/* instafeed.js | v2.0.0-rc3 | https://github.com/stevenschobert/instafeed.js | License: MIT */
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self,
global.Instafeed = factory());
})(this, function() {
"use strict";
function assert(val, msg) {
if (!val) {
throw new Error(msg);
}
}
function Instafeed(options) {
assert(!options || typeof options === "object", "options must be an object, got " + options + " (" + typeof options + ")");
var opts = {
accessToken: null,
accessTokenTimeout: 1e4,
after: null,
apiTimeout: 1e4,
apiLimit: null,
before: null,
debug: false,
error: null,
filter: null,
limit: null,
mock: false,
render: null,
sort: null,
success: null,
target: "instafeed",
template: '<img title="{{caption}}" src="{{image}}" />',
templateBoundaries: ["{{", "}}"],
transform: null
};
var state = {
running: false,
node: null,
token: null,
paging: null,
pool: []
};
if (options) {
for (var optKey in opts) {
if (typeof options[optKey] !== "undefined") {
opts[optKey] = options[optKey];
}
}
}
assert(typeof opts.target === "string" || typeof opts.target === "object", "target must be a string or DOM node, got " + opts.target + " (" + typeof opts.target + ")");
assert(typeof opts.accessToken === "string" || typeof opts.accessToken === "function", "accessToken must be a string or function, got " + opts.accessToken + " (" + typeof opts.accessToken + ")");
assert(typeof opts.accessTokenTimeout === "number", "accessTokenTimeout must be a number, got " + opts.accessTokenTimeout + " (" + typeof opts.accessTokenTimeout + ")");
assert(typeof opts.apiTimeout === "number", "apiTimeout must be a number, got " + opts.apiTimeout + " (" + typeof opts.apiTimeout + ")");
assert(typeof opts.debug === "boolean", "debug must be true or false, got " + opts.debug + " (" + typeof opts.debug + ")");
assert(typeof opts.mock === "boolean", "mock must be true or false, got " + opts.mock + " (" + typeof opts.mock + ")");
assert(typeof opts.templateBoundaries === "object" && opts.templateBoundaries.length === 2 && typeof opts.templateBoundaries[0] === "string" && typeof opts.templateBoundaries[1] === "string", "templateBoundaries must be an array of 2 strings, got " + opts.templateBoundaries + " (" + typeof opts.templateBoundaries + ")");
assert(!opts.template || typeof opts.template === "string", "template must null or string, got " + opts.template + " (" + typeof opts.template + ")");
assert(!opts.error || typeof opts.error === "function", "error must be null or function, got " + opts.error + " (" + typeof opts.error + ")");
assert(!opts.before || typeof opts.before === "function", "before must be null or function, got " + opts.before + " (" + typeof opts.before + ")");
assert(!opts.after || typeof opts.after === "function", "after must be null or function, got " + opts.after + " (" + typeof opts.after + ")");
assert(!opts.success || typeof opts.success === "function", "success must be null or function, got " + opts.success + " (" + typeof opts.success + ")");
assert(!opts.filter || typeof opts.filter === "function", "filter must be null or function, got " + opts.filter + " (" + typeof opts.filter + ")");
assert(!opts.transform || typeof opts.transform === "function", "transform must be null or function, got " + opts.transform + " (" + typeof opts.transform + ")");
assert(!opts.sort || typeof opts.sort === "function", "sort must be null or function, got " + opts.sort + " (" + typeof opts.sort + ")");
assert(!opts.render || typeof opts.render === "function", "render must be null or function, got " + opts.render + " (" + typeof opts.render + ")");
assert(!opts.limit || typeof opts.limit === "number", "limit must be null or number, got " + opts.limit + " (" + typeof opts.limit + ")");
assert(!opts.apiLimit || typeof opts.apiLimit === "number", "apiLimit must null or number, got " + opts.apiLimit + " (" + typeof opts.apiLimit + ")");
this._state = state;
this._options = opts;
}
Instafeed.prototype.run = function run() {
var scope = this;
this._debug("run", "options", this._options);
this._debug("run", "state", this._state);
if (this._state.running) {
this._debug("run", "already running, skipping");
return false;
}
this._start();
this._debug("run", "getting dom node");
if (typeof this._options.target === "string") {
this._state.node = document.getElementById(this._options.target);
} else {
this._state.node = this._options.target;
}
if (!this._state.node) {
this._fail(new Error("no element found with ID " + this._options.target));
return false;
}
this._debug("run", "got dom node", this._state.node);
this._debug("run", "getting access token");
this._getAccessToken(function onTokenReceived(err, token) {
if (err) {
scope._debug("onTokenReceived", "error", err);
scope._fail(new Error("error getting access token: " + err.message));
return;
}
scope._debug("onTokenReceived", "got token", token);
scope._state.token = token;
scope._showNext(function onNextShown(err) {
if (err) {
scope._debug("onNextShown", "error", err);
scope._fail(err);
return;
}
scope._finish();
});
});
return true;
};
Instafeed.prototype.hasNext = function hasNext() {
var paging = this._state.paging;
var pool = this._state.pool;
this._debug("hasNext", "paging", paging);
this._debug("hasNext", "pool", pool.length, pool);
return pool.length > 0 || paging && typeof paging.next === "string";
};
Instafeed.prototype.next = function next() {
var scope = this;
if (!scope.hasNext()) {
scope._debug("next", "hasNext is false, skipping");
return false;
}
if (scope._state.running) {
scope._debug("next", "already running, skipping");
return false;
}
scope._start();
scope._showNext(function onNextShown(err) {
if (err) {
scope._debug("onNextShown", "error", err);
scope._fail(err);
return;
}
scope._finish();
});
};
Instafeed.prototype._showNext = function showNext(callback) {
var scope = this;
var url = null;
var poolItems = null;
var hasLimit = typeof this._options.limit === "number";
scope._debug("showNext", "pool", scope._state.pool.length, scope._state.pool);
if (scope._state.pool.length > 0) {
if (hasLimit) {
poolItems = scope._state.pool.splice(0, scope._options.limit);
} else {
poolItems = scope._state.pool.splice(0);
}
scope._debug("showNext", "items from pool", poolItems.length, poolItems);
scope._debug("showNext", "updated pool", scope._state.pool.length, scope._state.pool);
if (scope._options.mock) {
scope._debug("showNext", "mock enabled, skipping render");
} else {
try {
scope._renderData(poolItems);
} catch (renderErr) {
callback(renderErr);
return;
}
}
callback(null);
} else {
if (scope._state.paging && typeof scope._state.paging.next === "string") {
url = scope._state.paging.next;
} else {
url = "https://graph.instagram.com/me/media?fields=caption,id,media_type,media_url,permalink,thumbnail_url,timestamp,username&access_token=" + scope._state.token;
if (!scope._options.apiLimit && typeof scope._options.limit === "number") {
scope._debug("showNext", "no apiLimit set, falling back to limit", scope._options.apiLimit, scope._options.limit);
url = url + "&limit=" + scope._options.limit;
} else if (typeof scope._options.apiLimit === "number") {
scope._debug("showNext", "apiLimit set, overriding limit", scope._options.apiLimit, scope._options.limit);
url = url + "&limit=" + scope._options.apiLimit;
}
}
scope._debug("showNext", "making request", url);
scope._makeApiRequest(url, function onResponseReceived(err, data) {
var processed = null;
if (err) {
scope._debug("onResponseReceived", "error", err);
callback(new Error("api request error: " + err.message));
return;
}
scope._debug("onResponseReceived", "data", data);
scope._success(data);
scope._debug("onResponseReceived", "setting paging", data.paging);
scope._state.paging = data.paging;
try {
processed = scope._processData(data);
scope._debug("onResponseReceived", "processed data", processed);
if (processed.unused && processed.unused.length > 0) {
scope._debug("onResponseReceived", "saving unused to pool", processed.unused.length, processed.unused);
for (var i = 0; i < processed.unused.length; i++) {
scope._state.pool.push(processed.unused[i]);
}
}
} catch (processErr) {
callback(processErr);
return;
}
if (scope._options.mock) {
scope._debug("onResponseReceived", "mock enabled, skipping append");
} else {
try {
scope._renderData(processed.items);
} catch (renderErr) {
callback(renderErr);
return;
}
}
callback(null);
});
}
};
Instafeed.prototype._processData = function processData(data) {
var hasTransform = typeof this._options.transform === "function";
var hasFilter = typeof this._options.filter === "function";
var hasSort = typeof this._options.sort === "function";
var hasLimit = typeof this._options.limit === "number";
var transformedFiltered = [];
var limitDelta = null;
var dataItem = null;
var transformedItem = null;
var filterResult = null;
var unusedItems = null;
this._debug("processData", "hasFilter", hasFilter, "hasTransform", hasTransform, "hasSort", hasSort, "hasLimit", hasLimit);
if (typeof data !== "object" || typeof data.data !== "object" || data.data.length <= 0) {
return null;
}
for (var i = 0; i < data.data.length; i++) {
dataItem = this._getItemData(data.data[i]);
if (hasTransform) {
try {
transformedItem = this._options.transform(dataItem);
this._debug("processData", "transformed item", dataItem, transformedItem);
} catch (err) {
this._debug("processData", "error calling transform", err);
throw new Error("error in transform: " + err.message);
}
} else {
transformedItem = dataItem;
}
if (hasFilter) {
try {
filterResult = this._options.filter(transformedItem);
this._debug("processData", "filter item result", transformedItem, filterResult);
} catch (err) {
this._debug("processData", "error calling filter", err);
throw new Error("error in filter: " + err.message);
}
if (filterResult) {
transformedFiltered.push(transformedItem);
}
} else {
transformedFiltered.push(transformedItem);
}
}
if (hasSort) {
try {
transformedFiltered.sort(this._options.sort);
} catch (err) {
this._debug("processData", "error calling sort", err);
throw new Error("error in sort: " + err.message);
}
}
if (hasLimit) {
limitDelta = transformedFiltered.length - this._options.limit;
this._debug("processData", "checking limit", transformedFiltered.length, this._options.limit, limitDelta);
if (limitDelta > 0) {
unusedItems = transformedFiltered.slice(transformedFiltered.length - limitDelta);
this._debug("processData", "unusedItems", unusedItems.length, unusedItems);
transformedFiltered.splice(transformedFiltered.length - limitDelta, limitDelta);
}
}
return {
items: transformedFiltered,
unused: unusedItems
};
};
Instafeed.prototype._extractTags = function extractTags(str) {
var exp = /#([^\s]+)/gi;
var badChars = /[~`!##$%^&*\(\)\-\+={}\[\]:;"'<>\?,\./|\\\s]+/i;
var tags = [];
var match = null;
if (typeof str === "string") {
while ((match = exp.exec(str)) !== null) {
if (badChars.test(match[1]) === false) {
tags.push(match[1]);
}
}
}
return tags;
};
Instafeed.prototype._getItemData = function getItemData(data) {
var type = null;
var image = null;
switch (data.media_type) {
case "IMAGE":
type = "image";
image = data.media_url;
break;
case "VIDEO":
type = "video";
image = data.thumbnail_url;
break;
case "CAROUSEL_ALBUM":
type = "album";
image = data.media_url;
break;
}
return {
caption: data.caption,
tags: this._extractTags(data.caption),
id: data.id,
image: image,
link: data.permalink,
model: data,
timestamp: data.timestamp,
type: type,
username: data.username
};
};
Instafeed.prototype._renderData = function renderData(items) {
var hasTemplate = typeof this._options.template === "string";
var hasRender = typeof this._options.render === "function";
var item = null;
var itemHtml = null;
var container = null;
var html = "";
this._debug("renderData", "hasTemplate", hasTemplate, "hasRender", hasRender);
if (typeof items !== "object" || items.length <= 0) {
return;
}
for (var i = 0; i < items.length; i++) {
item = items[i];
if (hasRender) {
try {
itemHtml = this._options.render(item, this._options);
this._debug("renderData", "custom render result", item, itemHtml);
} catch (err) {
this._debug("renderData", "error calling render", err);
throw new Error("error in render: " + err.message);
}
} else if (hasTemplate) {
itemHtml = this._basicRender(item);
}
if (itemHtml) {
html = html + itemHtml;
} else {
this._debug("renderData", "render item did not return any content", item);
}
}
this._debug("renderData", "html content", html);
container = document.createElement("div");
container.innerHTML = html;
this._debug("renderData", "container", container, container.childNodes.length, container.childNodes);
while (container.childNodes.length > 0) {
this._debug("renderData", "appending child", container.childNodes[0]);
this._state.node.appendChild(container.childNodes[0]);
}
};
Instafeed.prototype._basicRender = function basicRender(data) {
var exp = new RegExp(this._options.templateBoundaries[0] + "([\\s\\w.]+)" + this._options.templateBoundaries[1], "gm");
var template = this._options.template;
var match = null;
var output = "";
var substr = null;
var lastIndex = 0;
var keyPath = null;
var keyPathValue = null;
while ((match = exp.exec(template)) !== null) {
keyPath = match[1];
substr = template.slice(lastIndex, match.index);
output = output + substr;
keyPathValue = this._valueForKeyPath(keyPath, data);
if (keyPathValue) {
output = output + keyPathValue.toString();
}
lastIndex = exp.lastIndex;
}
if (lastIndex < template.length) {
substr = template.slice(lastIndex, template.length);
output = output + substr;
}
return output;
};
Instafeed.prototype._valueForKeyPath = function valueForKeyPath(keyPath, data) {
var exp = /([\w]+)/gm;
var match = null;
var key = null;
var lastValue = data;
while ((match = exp.exec(keyPath)) !== null) {
if (typeof lastValue !== "object") {
return null;
}
key = match[1];
lastValue = lastValue[key];
}
return lastValue;
};
Instafeed.prototype._fail = function fail(err) {
var didHook = this._runHook("error", err);
if (!didHook && console && typeof console.error === "function") {
console.error(err);
}
this._state.running = false;
};
Instafeed.prototype._start = function start() {
this._state.running = true;
this._runHook("before");
};
Instafeed.prototype._finish = function finish() {
this._runHook("after");
this._state.running = false;
};
Instafeed.prototype._success = function success(data) {
this._runHook("success", data);
this._state.running = false;
};
Instafeed.prototype._makeApiRequest = function makeApiRequest(url, callback) {
var called = false;
var scope = this;
var apiRequest = null;
var callbackOnce = function callbackOnce(err, value) {
if (!called) {
called = true;
callback(err, value);
}
};
apiRequest = new XMLHttpRequest();
apiRequest.ontimeout = function apiRequestTimedOut() {
callbackOnce(new Error("api request timed out"));
};
apiRequest.onerror = function apiRequestOnError() {
callbackOnce(new Error("api connection error"));
};
apiRequest.onload = function apiRequestOnLoad(event) {
var contentType = apiRequest.getResponseHeader("Content-Type");
var responseJson = null;
scope._debug("apiRequestOnLoad", "loaded", event);
scope._debug("apiRequestOnLoad", "response status", apiRequest.status);
scope._debug("apiRequestOnLoad", "response content type", contentType);
if (contentType.indexOf("application/json") >= 0) {
try {
responseJson = JSON.parse(apiRequest.responseText);
} catch (err) {
scope._debug("apiRequestOnLoad", "json parsing error", err, apiRequest.responseText);
callbackOnce(new Error("error parsing response json"));
return;
}
}
if (apiRequest.status !== 200) {
if (responseJson && responseJson.error) {
callbackOnce(new Error(responseJson.error.code + " " + responseJson.error.message));
} else {
callbackOnce(new Error("status code " + apiRequest.status));
}
return;
}
callbackOnce(null, responseJson);
};
apiRequest.open("GET", url, true);
apiRequest.timeout = this._options.apiTimeout;
apiRequest.send();
};
Instafeed.prototype._getAccessToken = function getAccessToken(callback) {
var called = false;
var scope = this;
var timeoutCheck = null;
var callbackOnce = function callbackOnce(err, value) {
if (!called) {
called = true;
clearTimeout(timeoutCheck);
callback(err, value);
}
};
if (typeof this._options.accessToken === "function") {
this._debug("getAccessToken", "calling accessToken as function");
timeoutCheck = setTimeout(function accessTokenTimeoutCheck() {
scope._debug("getAccessToken", "timeout check", called);
callbackOnce(new Error("accessToken timed out"), null);
}, this._options.accessTokenTimeout);
try {
this._options.accessToken(function accessTokenReceiver(err, value) {
scope._debug("getAccessToken", "received accessToken callback", called, err, value);
callbackOnce(err, value);
});
} catch (err) {
this._debug("getAccessToken", "error invoking the accessToken as function", err);
callbackOnce(err, null);
}
} else {
this._debug("getAccessToken", "treating accessToken as static", typeof this._options.accessToken);
callbackOnce(null, this._options.accessToken);
}
};
Instafeed.prototype._debug = function debug() {
var args = null;
if (this._options.debug && console && typeof console.log === "function") {
args = [].slice.call(arguments);
args[0] = "[Instafeed] [" + args[0] + "]";
console.log.apply(null, args);
}
};
Instafeed.prototype._runHook = function runHook(hookName, data) {
var success = false;
if (typeof this._options[hookName] === "function") {
try {
this._options[hookName](data);
success = true;
} catch (err) {
this._debug("runHook", "error calling hook", hookName, err);
}
}
return success;
};
return Instafeed;
});
$.ajax({
type: 'get',
dataType: 'json',
url: 'https://ig.instant-tokens.com/users/133af082-bd46-416f-8d95-b6ca28a08bee/instagram/17841406882807948/token?userSecret=slqh9w7letquro8mj056yi',
success: function(response) {
var feed = new Instafeed({
target: 'instafeed',
accessToken: response.Token, // Access token from json response
});
feed.run();
},
});
Thanks for all the suggestions, I really appreciate it!
Related
Image Here
Hello! I am trying to add a search bar that acts like a proxy at the top of my website. Whenever I input a website like https://stackoverflow.com I receive an error on the website. RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599] (Note: I am using the ultraviolet service) If you'd like to test yourself the website is https://lun.netlify.app also no errors seem to appear in the console log.
importScripts('/uv/uv.bundle.js');
importScripts('/uv/uv.config.js');
class UVServiceWorker extends EventEmitter {
constructor(config = __uv$config) {
super();
if (!config.bare) config.bare = '/bare/';
this.addresses = typeof config.bare === 'string' ? [ new URL(config.bare, location) ] : config.bare.map(str => new URL(str, location));
this.headers = {
csp: [
'cross-origin-embedder-policy',
'cross-origin-opener-policy',
'cross-origin-resource-policy',
'content-security-policy',
'content-security-policy-report-only',
'expect-ct',
'feature-policy',
'origin-isolation',
'strict-transport-security',
'upgrade-insecure-requests',
'x-content-type-options',
'x-download-options',
'x-frame-options',
'x-permitted-cross-domain-policies',
'x-powered-by',
'x-xss-protection',
],
forward: [
'accept-encoding',
'connection',
'content-length',
'content-type',
'user-agent',
],
};
this.method = {
empty: [
'GET',
'HEAD'
]
};
this.statusCode = {
empty: [
204,
304,
],
};
this.config = config;
};
async fetch({ request }) {
if (!request.url.startsWith(location.origin + (this.config.prefix || '/service/'))) {
return fetch(request);
};
try {
const ultraviolet = new Ultraviolet(this.config);
if (typeof this.config.construct === 'function') {
this.config.construct(ultraviolet, 'service');
};
const db = await ultraviolet.cookie.db();
ultraviolet.meta.origin = location.origin;
ultraviolet.meta.base = ultraviolet.meta.url = new URL(ultraviolet.sourceUrl(request.url));
const requestCtx = new RequestContext(
request,
this,
ultraviolet,
!this.method.empty.includes(request.method.toUpperCase()) ? await request.blob() : null
);
if (ultraviolet.meta.url.protocol === 'blob:') {
requestCtx.blob = true;
requestCtx.base = requestCtx.url = new URL(requestCtx.url.pathname);
};
if (request.referrer && request.referrer.startsWith(location.origin)) {
const referer = new URL(ultraviolet.sourceUrl(request.referrer));
if (ultraviolet.meta.url.origin !== referer.origin && request.mode === 'cors') {
requestCtx.headers.origin = referer.origin;
};
requestCtx.headers.referer = referer.href;
};
const cookies = await ultraviolet.cookie.getCookies(db) || [];
const cookieStr = ultraviolet.cookie.serialize(cookies, ultraviolet.meta, false);
const browser = Ultraviolet.Bowser.getParser(self.navigator.userAgent).getBrowserName();
if (browser === 'Firefox' && !(request.destination === 'iframe' || request.destination === 'document')) {
requestCtx.forward.shift();
};
if (cookieStr) requestCtx.headers.cookie = cookieStr;
const reqEvent = new HookEvent(requestCtx, null, null);
this.emit('request', reqEvent);
if (reqEvent.intercepted) return reqEvent.returnValue;
const response = await fetch(requestCtx.send);
if (response.status === 500) {
return Promise.reject('');
};
const responseCtx = new ResponseContext(requestCtx, response, this);
const resEvent = new HookEvent(responseCtx, null, null);
this.emit('beforemod', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
for (const name of this.headers.csp) {
if (responseCtx.headers[name]) delete responseCtx.headers[name];
};
if (responseCtx.headers.location) {
responseCtx.headers.location = ultraviolet.rewriteUrl(responseCtx.headers.location);
};
if (responseCtx.headers['set-cookie']) {
Promise.resolve(ultraviolet.cookie.setCookies(responseCtx.headers['set-cookie'], db, ultraviolet.meta)).then(() => {
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: 'updateCookies',
url: ultraviolet.meta.url.href,
});
});
});
});
delete responseCtx.headers['set-cookie'];
};
if (responseCtx.body) {
switch(request.destination) {
case 'script':
case 'worker':
responseCtx.body = `if (!self.__uv && self.importScripts) importScripts('${__uv$config.bundle}', '${__uv$config.config}', '${__uv$config.handler}');\n`;
responseCtx.body += ultraviolet.js.rewrite(
await response.text()
);
break;
case 'style':
responseCtx.body = ultraviolet.rewriteCSS(
await response.text()
);
break;
case 'iframe':
case 'document':
if (isHtml(ultraviolet.meta.url, (responseCtx.headers['content-type'] || ''))) {
responseCtx.body = ultraviolet.rewriteHtml(
await response.text(),
{
document: true ,
injectHead: ultraviolet.createHtmlInject(
this.config.handler,
this.config.bundle,
this.config.config,
ultraviolet.cookie.serialize(cookies, ultraviolet.meta, true),
request.referrer
)
}
);
};
};
};
if (requestCtx.headers.accept === 'text/event-stream') {
responseCtx.headers['content-type'] = 'text/event-stream';
};
this.emit('response', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
return new Response(responseCtx.body, {
headers: responseCtx.headers,
status: responseCtx.status,
statusText: responseCtx.statusText,
});
} catch(err) {
return new Response(err.toString(), {
status: 500,
});
};
};
getBarerResponse(response) {
const headers = {};
const raw = JSON.parse(response.headers.get('x-bare-headers'));
for (const key in raw) {
headers[key.toLowerCase()] = raw[key];
};
return {
headers,
status: +response.headers.get('x-bare-status'),
statusText: response.headers.get('x-bare-status-text'),
body: !this.statusCode.empty.includes(+response.headers.get('x-bare-status')) ? response.body : null,
};
};
get address() {
return this.addresses[Math.floor(Math.random() * this.addresses.length)];
};
static Ultraviolet = Ultraviolet;
};
self.UVServiceWorker = UVServiceWorker;
class ResponseContext {
constructor(request, response, worker) {
const { headers, status, statusText, body } = !request.blob ? worker.getBarerResponse(response) : {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
body: response.body,
};
this.request = request;
this.raw = response;
this.ultraviolet = request.ultraviolet;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.body = body;
};
get url() {
return this.request.url;
}
get base() {
return this.request.base;
};
set base(val) {
this.request.base = val;
};
};
class RequestContext {
constructor(request, worker, ultraviolet, body = null) {
this.ultraviolet = ultraviolet;
this.request = request;
this.headers = Object.fromEntries([...request.headers.entries()]);
this.method = request.method;
this.forward = [...worker.headers.forward];
this.address = worker.address;
this.body = body || null;
this.redirect = request.redirect;
this.credentials = 'omit';
this.mode = request.mode === 'cors' ? request.mode : 'same-origin';
this.blob = false;
};
get send() {
return new Request((!this.blob ? this.address.href + 'v1/' : 'blob:' + location.origin + this.url.pathname), {
method: this.method,
headers: {
'x-bare-protocol': this.url.protocol,
'x-bare-host': this.url.hostname,
'x-bare-path': this.url.pathname + this.url.search,
'x-bare-port': this.url.port || (this.url.protocol === 'https:' ? '443' : '80'),
'x-bare-headers': JSON.stringify(this.headers),
'x-bare-forward-headers': JSON.stringify(this.forward),
},
redirect: this.redirect,
credentials: this.credentials,
mode: location.origin !== this.address.origin ? 'cors' : this.mode,
body: this.body
});
};
get url() {
return this.ultraviolet.meta.url;
};
set url(val) {
this.ultraviolet.meta.url = val;
};
get base() {
return this.ultraviolet.meta.base;
};
set base(val) {
this.ultraviolet.meta.base = val;
};
}
function isHtml(url, contentType = '') {
return (Ultraviolet.mime.contentType((contentType || url.pathname)) || 'text/html').split(';')[0] === 'text/html';
};
class HookEvent {
#intercepted;
#returnValue;
constructor(data = {}, target = null, that = null) {
this.#intercepted = false;
this.#returnValue = null;
this.data = data;
this.target = target;
this.that = that;
};
get intercepted() {
return this.#intercepted;
};
get returnValue() {
return this.#returnValue;
};
respondWith(input) {
this.#returnValue = input;
this.#intercepted = true;
};
};
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
I need to send data from a custom form to Zoho. I'm looking at the native javascript request in their documentation here.
https://www.zoho.com/crm/developer/docs/api/v2/insert-records.html
var listener = 0;
class InsertRecordsAPI {
async insertRecords() {
var url = "https://www.zohoapis.com/crm/v2/Leads"
var parameters = new Map()
var headers = new Map()
var token = {
clientId:"1000.NPY9M1V0XXXXXXXXXXXXXXXXXXXF7H",
redirectUrl:"http://127.0.0.1:5500/redirect.html",
scope:"ZohoCRM.users.ALL,ZohoCRM.bulk.read,ZohoCRM.modules.ALL,ZohoCRM.settings.ALL,Aaaserver.profile.Read,ZohoCRM.org.ALL,profile.userphoto.READ,ZohoFiles.files.ALL,ZohoCRM.bulk.ALL,ZohoCRM.settings.variable_groups.ALL"
}
var accesstoken = await new InsertRecordsAPI().getToken(token)
headers.set("Authorization", "Zoho-oauthtoken " + accesstoken)
var requestMethod = "POST"
var reqBody = {"data":[{"Last_Name":"Lead_changed","Email":"newcrmapi#zoho.com","Company":"abc","Lead_Status":"Contacted"},{"Last_Name":"New Lead","Email":"newlead#zoho.com","Company":"abc","Lead_Status":"Contacted"}],"trigger":["approval","workflow","blueprint"]}
var params = "";
parameters.forEach(function(value, key) {
if (parameters.has(key)) {
if (params) {
params = params + key + '=' + value + '&';
}
else {
params = key + '=' + value + '&';
}
}
});
var apiHeaders = {};
if(headers) {
headers.forEach(function(value, key) {
apiHeaders[key] = value;
});
}
if (params.length > 0){
url = url + '?' + params.substring(0, params.length - 1);
}
var requestObj = {
uri : url,
method : requestMethod,
headers : apiHeaders,
body : JSON.stringify(reqBody),
encoding: "utf8",
allowGetBody : true,
throwHttpErrors : false
};
var result = await new InsertRecordsAPI().makeAPICall(requestObj);
console.log(result.status)
console.log(result.response)
}
async getToken(token) {
if(listener == 0) {
window.addEventListener("storage", function(reponse) {
if(reponse.key === "access_token" && (reponse.oldValue != reponse.newValue || reponse.oldValue == null)){
location.reload();
}
if(reponse.key === "access_token"){
sessionStorage.removeItem("__auth_process");
}
}, false);
listener = 1;
if(sessionStorage.getItem("__auth_process")) {
sessionStorage.removeItem("__auth_process");
}
}
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists) {
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
var valueInStore = sessionStorage.getItem("access_token");
var tokenInit = sessionStorage.getItem("__token_init");
if(tokenInit != null && valueInStore != null && Date.now() >= parseInt(tokenInit) + 59 * 60 * 1000){ // check after 59th minute
valueInStore = null;
sessionStorage.removeItem("access_token");
}
var auth_process = sessionStorage.getItem("__auth_process");
if ((valueInStore == null && auth_process == null) || (valueInStore == 'undefined' && (auth_process == null || auth_process == "true"))) {
var accountsUrl = "https://accounts.zoho.com/oauth/v2/auth"
var clientId;
var scope;
var redirectUrl;
if(token != null) {
clientId = token.clientId;
scope = token.scope;
redirectUrl = token.redirectUrl;
}
var fullGrant = sessionStorage.getItem("full_grant");
var grantedForSession = sessionStorage.getItem("granted_for_session");
if(sessionStorage.getItem("__token_init") != null && ((fullGrant != null && "true" == full_grant) || (grantedForSession != null && "true" == grantedForSession))) {
accountsUrl += '/refresh';
}
if (clientId && scope) {
sessionStorage.setItem("__token_init", Date.now());
sessionStorage.removeItem("access_token");
sessionStorage.setItem("__auth_process", "true");
window.open(accountsUrl + "?" + "scope" + "=" + scope + "&"+ "client_id" +"=" + clientId + "&response_type=token&state=zohocrmclient&redirect_uri=" + redirectUrl);
["granted_for_session", "access_token","expires_in","expires_in_sec","location","api_domain","state","__token_init","__auth_process"].forEach(function (k) {
var isKeyExists = localStorage.hasOwnProperty(k);
if(isKeyExists){
sessionStorage.setItem(k, localStorage[k]);
}
localStorage.removeItem(k);
});
valueInStore = sessionStorage.getItem("access_token");
}
}
if(token != null && valueInStore != 'undefined'){
token.accessToken = valueInStore;
}
return token.accessToken;
}
async makeAPICall(requestDetails) {
return new Promise(function (resolve, reject) {
var body, xhr, i;
body = requestDetails.body || null;
xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(requestDetails.method, requestDetails.uri, true);
for (i in requestDetails.headers) {
xhr.setRequestHeader(i, requestDetails.headers[i]);
}
xhr.send(body);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
resolve(xhr);
}
}
})
}
}
I need to send dynamic data and I'm a little fuzzy on how to use the async functions and populate the reqBody variable.
I have tried things like
makeAPICall(myjson);
.then((data) => { console.log(data)})
But I'm not getting anything returned. Any response is welcome. My thanks in advance.
I'm using xml2json for the first time to get an review feed to populate on a website and I keep getting errors such as;
Uncaught ReferenceError: X2JS is not defined
and
Uncaught TypeError: Cannot set property 'X2JS' of undefined
I can't seem to find a solution, this is the code;
jQuery(document).ready(function() {
//below here
//API Feed for Testimonials
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports === "object") {
module.exports = factory();
} else {
root.X2JS = factory();
}
}(this, function () {
return function (config) {
'use strict';
var VERSION = "1.2.0";
config = config || {};
initConfigDefaults();
initRequiredPolyfills();
function initConfigDefaults() {
if(config.escapeMode === undefined) {
config.escapeMode = true;
}
config.attributePrefix = config.attributePrefix || "_";
config.arrayAccessForm = config.arrayAccessForm || "none";
config.emptyNodeForm = config.emptyNodeForm || "text";
if(config.enableToStringFunc === undefined) {
config.enableToStringFunc = true;
}
config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
if(config.skipEmptyTextNodesForObj === undefined) {
config.skipEmptyTextNodesForObj = true;
}
if(config.stripWhitespaces === undefined) {
config.stripWhitespaces = true;
}
config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
if(config.useDoubleQuotes === undefined) {
config.useDoubleQuotes = false;
}
config.xmlElementsFilter = config.xmlElementsFilter || [];
config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
if(config.keepCData === undefined) {
config.keepCData = false;
}
}
var DOMNodeTypes = {
ELEMENT_NODE : 1,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9
};
function initRequiredPolyfills() {
}
function getNodeLocalName( node ) {
var nodeLocalName = node.localName;
if(nodeLocalName == null) // Yeah, this is IE!!
nodeLocalName = node.baseName;
if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too
nodeLocalName = node.nodeName;
return nodeLocalName;
}
function getNodePrefix(node) {
return node.prefix;
}
function escapeXmlChars(str) {
if(typeof(str) == "string")
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
else
return str;
}
function unescapeXmlChars(str) {
return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
}
function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
var idx = 0;
for(; idx < stdFiltersArrayForm.length; idx++) {
var filterPath = stdFiltersArrayForm[idx];
if( typeof filterPath === "string" ) {
if(filterPath == path)
break;
}
else
if( filterPath instanceof RegExp) {
if(filterPath.test(path))
break;
}
else
if( typeof filterPath === "function") {
if(filterPath(obj, name, path))
break;
}
}
return idx!=stdFiltersArrayForm.length;
}
function toArrayAccessForm(obj, childName, path) {
switch(config.arrayAccessForm) {
case "property":
if(!(obj[childName] instanceof Array))
obj[childName+"_asArray"] = [obj[childName]];
else
obj[childName+"_asArray"] = obj[childName];
break;
/*case "none":
break;*/
}
if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
obj[childName] = [obj[childName]];
}
}
}
function fromXmlDateTime(prop) {
// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
// Improved to support full spec and optional parts
var bits = prop.split(/[-T:+Z]/g);
var d = new Date(bits[0], bits[1]-1, bits[2]);
var secondBits = bits[5].split("\.");
d.setHours(bits[3], bits[4], secondBits[0]);
if(secondBits.length>1)
d.setMilliseconds(secondBits[1]);
// Get supplied time zone offset in minutes
if(bits[6] && bits[7]) {
var offsetMinutes = bits[6] * 60 + Number(bits[7]);
var sign = /\d\d-\d\d:\d\d$/.test(prop)? '-' : '+';
// Apply the sign
offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);
// Apply offset and local timezone
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())
}
else
if(prop.indexOf("Z", prop.length - 1) !== -1) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
}
// d is now a local time equivalent to the supplied time
return d;
}
function checkFromXmlDateTimePaths(value, childName, fullPath) {
if(config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
return fromXmlDateTime(value);
}
else
return value;
}
else
return value;
}
function checkXmlElementsFilter(obj, childType, childName, childPath) {
if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
}
else
return true;
}
function parseDOMChildren( node, path ) {
if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
var result = new Object;
var nodeChildren = node.childNodes;
// Alternative for firstElementChild which is not supported in some environments
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx);
if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var childName = getNodeLocalName(child);
result[childName] = parseDOMChildren(child, childName);
}
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var result = new Object;
result.__cnt=0;
var nodeChildren = node.childNodes;
// Children nodes
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx); // nodeChildren[cidx];
var childName = getNodeLocalName(child);
if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {
var childPath = path+"."+childName;
if (checkXmlElementsFilter(result,child.nodeType,childName,childPath)) {
result.__cnt++;
if(result[childName] == null) {
result[childName] = parseDOMChildren(child, childPath);
toArrayAccessForm(result, childName, childPath);
}
else {
if(result[childName] != null) {
if( !(result[childName] instanceof Array)) {
result[childName] = [result[childName]];
toArrayAccessForm(result, childName, childPath);
}
}
(result[childName])[result[childName].length] = parseDOMChildren(child, childPath);
}
}
}
}
// Attributes
for(var aidx=0; aidx <node.attributes.length; aidx++) {
var attr = node.attributes.item(aidx); // [aidx];
result.__cnt++;
result[config.attributePrefix+attr.name]=attr.value;
}
// Node namespace prefix
var nodePrefix = getNodePrefix(node);
if(nodePrefix!=null && nodePrefix!="") {
result.__cnt++;
result.__prefix=nodePrefix;
}
if(result["#text"]!=null) {
result.__text = result["#text"];
if(result.__text instanceof Array) {
result.__text = result.__text.join("\n");
}
//if(config.escapeMode)
// result.__text = unescapeXmlChars(result.__text);
if(config.stripWhitespaces)
result.__text = result.__text.trim();
delete result["#text"];
if(config.arrayAccessForm=="property")
delete result["#text_asArray"];
result.__text = checkFromXmlDateTimePaths(result.__text, childName, path+"."+childName);
}
if(result["#cdata-section"]!=null) {
result.__cdata = result["#cdata-section"];
delete result["#cdata-section"];
if(config.arrayAccessForm=="property")
delete result["#cdata-section_asArray"];
}
if( result.__cnt == 0 && config.emptyNodeForm=="text" ) {
result = '';
}
else
if( result.__cnt == 1 && result.__text!=null ) {
result = result.__text;
}
else
if( result.__cnt == 1 && result.__cdata!=null && !config.keepCData ) {
result = result.__cdata;
}
else
if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {
if( (config.stripWhitespaces && result.__text=="") || (result.__text.trim()=="")) {
delete result.__text;
}
}
delete result.__cnt;
if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {
result.toString = function() {
return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');
};
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
return node.nodeValue;
}
}
function startTag(jsonObj, element, attrList, closed) {
var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
if(attrList!=null) {
for(var aidx = 0; aidx < attrList.length; aidx++) {
var attrName = attrList[aidx];
var attrVal = jsonObj[attrName];
if(config.escapeMode)
attrVal=escapeXmlChars(attrVal);
resultStr+=" "+attrName.substr(config.attributePrefix.length)+"=";
if(config.useDoubleQuotes)
resultStr+='"'+attrVal+'"';
else
resultStr+="'"+attrVal+"'";
}
}
if(!closed)
resultStr+=">";
else
resultStr+="/>";
return resultStr;
}
function endTag(jsonObj,elementName) {
return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {
if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray")))
|| jsonObjField.toString().indexOf(config.attributePrefix)==0
|| jsonObjField.toString().indexOf("__")==0
|| (jsonObj[jsonObjField] instanceof Function) )
return true;
else
return false;
}
function jsonXmlElemCount ( jsonObj ) {
var elementsCnt = 0;
if(jsonObj instanceof Object ) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) )
continue;
elementsCnt++;
}
}
return elementsCnt;
}
function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
return config.jsonPropertiesFilter.length == 0
|| jsonObjPath==""
|| checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
}
function parseJSONAttributes ( jsonObj ) {
var attrList = [];
if(jsonObj instanceof Object ) {
for( var ait in jsonObj ) {
if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {
attrList.push(ait);
}
}
}
return attrList;
}
function parseJSONTextAttrs ( jsonTxtObj ) {
var result ="";
if(jsonTxtObj.__cdata!=null) {
result+="<![CDATA["+jsonTxtObj.__cdata+"]]>";
}
if(jsonTxtObj.__text!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj.__text);
else
result+=jsonTxtObj.__text;
}
return result;
}
function parseJSONTextObject ( jsonTxtObj ) {
var result ="";
if( jsonTxtObj instanceof Object ) {
result+=parseJSONTextAttrs ( jsonTxtObj );
}
else
if(jsonTxtObj!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj);
else
result+=jsonTxtObj;
}
return result;
}
function getJsonPropertyPath(jsonObjPath, jsonPropName) {
if (jsonObjPath==="") {
return jsonPropName;
}
else
return jsonObjPath+"."+jsonPropName;
}
function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) {
var result = "";
if(jsonArrRoot.length == 0) {
result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);
}
else {
for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj));
result+=endTag(jsonArrRoot[arIdx],jsonArrObj);
}
}
return result;
}
function parseJSONObject ( jsonObj, jsonObjPath ) {
var result = "";
var elementsCnt = jsonXmlElemCount ( jsonObj );
if(elementsCnt > 0) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!="" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) )
continue;
var subObj = jsonObj[it];
var attrList = parseJSONAttributes( subObj )
if(subObj == null || subObj == undefined) {
result+=startTag(subObj, it, attrList, true);
}
else
if(subObj instanceof Object) {
if(subObj instanceof Array) {
result+=parseJSONArray( subObj, it, attrList, jsonObjPath );
}
else if(subObj instanceof Date) {
result+=startTag(subObj, it, attrList, false);
result+=subObj.toISOString();
result+=endTag(subObj,it);
}
else {
var subObjElementsCnt = jsonXmlElemCount ( subObj );
if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it));
result+=endTag(subObj,it);
}
else {
result+=startTag(subObj, it, attrList, true);
}
}
}
else {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONTextObject(subObj);
result+=endTag(subObj,it);
}
}
}
result+=parseJSONTextObject(jsonObj);
return result;
}
this.parseXmlString = function(xmlDocStr) {
var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
if (window.DOMParser) {
var parser=new window.DOMParser();
var parsererrorNS = null;
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
try {
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
//throw new Error('Error parsing XML: '+xmlDocStr);
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
}
else {
// IE :(
if(xmlDocStr.indexOf("<?")==0) {
xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
}
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlDocStr);
}
return xmlDoc;
};
this.asArray = function(prop) {
if (prop === undefined || prop == null)
return [];
else
if(prop instanceof Array)
return prop;
else
return [prop];
};
this.toXmlDateTime = function(dt) {
if(dt instanceof Date)
return dt.toISOString();
else
if(typeof(dt) === 'number' )
return new Date(dt).toISOString();
else
return null;
};
this.asDateTime = function(prop) {
if(typeof(prop) == "string") {
return fromXmlDateTime(prop);
}
else
return prop;
};
this.xml2json = function (xmlDoc) {
return parseDOMChildren ( xmlDoc );
};
this.xml_str2json = function (xmlDocStr) {
var xmlDoc = this.parseXmlString(xmlDocStr);
if(xmlDoc!=null)
return this.xml2json(xmlDoc);
else
return null;
};
this.json2xml_str = function (jsonObj) {
return parseJSONObject ( jsonObj, "" );
};
this.json2xml = function (jsonObj) {
var xmlDocStr = this.json2xml_str (jsonObj);
return this.parseXmlString(xmlDocStr);
};
this.getVersion = function () {
return VERSION;
};
}
}))
// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "";
jQuery.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) {
var xmlText = data,
x2js = new X2JS(),
jsonObj = x2js.xml_str2json( xmlText ),
html = '<div class="flex-wrapper">';
// console.log(jsonObj.SMART);
jQuery.each( jsonObj.SMART.XMLJSON, function( key, answer ) {
html += '<div class="flex-shell testimonial">';
html += '<div class="flex-item">';
html += '<div>';
html += '<span class="review-number"><i>' + answer.Quality + '</i> Quality of work</span>' ;
html += '<span class="review-number"><i>' + answer.Time + '</i> Timeliness</span>' ;
html += '<span class="review-number"><i>' + answer.Budget + '</i> Value for Money</span>' ;
html += '<span class="review-number"><i>' + answer.Courtesy + '</i> Courtesy</span>' ;
html += '<span class="review">' + answer.Testimonial + '</span>' ;
html += '<span class="name">' + answer.RefName + ' - ' + answer.refDate + '</span>';
html += '</div>';
html += '</div>';
html += '</div>';
});
jQuery('.start').html(html);
});
//above here
});
Apologies if I've gone about this in the wrong way. I've done;
npm install xml2json
Which didn't flag up any errors but I still can't seem to get the data to load correctly.
Solution that after you import <script> from package x2js, you should use window.X2JS to get constructor of X2JS. Almost packages implementing for both NPM and browser, the browser version usually use via object window, because it is shared and free connected in almost browsers.
This is my demo for the solution: https://jsfiddle.net/huynhsamha/2evdgt7r/
In my demo, I've include package x2js from NPM here https://unpkg.com/x2js#3.2.3/x2js.js
var X2JS = window.X2JS;
var x2js = new X2JS();
const data = {
a: {
b: 1
},
c: [1, 2]
}
console.log(x2js.js2xml(data))
// <a><b>1</b></a><c>1</c><c>2</c>
I've been at it all day trying to find a good solution to displaying a google calendar in a list format on a website i'm developing. I came across this piece of code which works quite well except a few formatting problems. I'm not all that clued up on jQuery so I'm struggling with the formatting. I've done as much as I can from the CSS side but clearly some of it is in the script side. Maybe if someone could please help me remove the formatting in the script and have strictly css that would be great =) or another better solution =P
Thanks so much!
The format i'm after is 3 sections in different divs:
date('nov 12, 09:00') event('Student Night') location('Nicci Beach')
JS:
// Generated by CoffeeScript 1.4.0
(function() {
var $, gCalFlow, log, methods, pad_zero, _ref;
$ = jQuery;
if ((typeof window !== "undefined" && window !== null) && (window._gCalFlow_debug != null) && (typeof console !== "undefined" && console !== null)) {
log = console;
if ((_ref = log.debug) == null) {
log.debug = log.log;
}
} else {
log = {};
log.error = log.warn = log.log = log.info = log.debug = function() {};
}
pad_zero = function(num, size) {
var i, ret, _i, _ref1;
if (size == null) {
size = 2;
}
if (10 * (size - 1) <= num) {
return num;
}
ret = "";
for (i = _i = 1, _ref1 = size - ("" + num).length; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 1 <= _ref1 ? ++_i : --_i) {
ret = ret.concat("0");
}
return ret.concat(num);
};
gCalFlow = (function() {
gCalFlow.prototype.target = null;
gCalFlow.prototype.template = $("<div class=\"gCalFlow\">\n <div class=\"gcf-header-block\">\n <div class=\"gcf-title-block\">\n <span class=\"gcf-title\"></span>\n </div>\n </div>\n <div class=\"gcf-item-container-block\">\n <div class=\"gcf-item-block\">\n <div class=\"gcf-item-header-block\">\n <div class=\"gcf-item-date-block\">\n [<span class=\"gcf-item-daterange\"></span>]\n </div>\n <div class=\"gcf-item-title-block\">\n <strong class=\"gcf-item-title\"></strong>\n </div>\n </div>\n <div class=\"gcf-item-body-block\">\n <div class=\"gcf-item-description\">\n </div>\n <div class=\"gcf-item-location\">\n </div>\n </div>\n </div>\n </div>\n <div class=\"gcf-last-update-block\">\n LastUpdate: <span class=\"gcf-last-update\"></span>\n </div>\n</div>");
gCalFlow.prototype.opts = {
maxitem: 5,
calid: null,
mode: 'upcoming',
feed_url: null,
auto_scroll: false,
scroll_interval: 10 * 1000,
link_title: true,
link_item_title: true,
link_item_description: true,
link_target: '_blank',
item_description_in_html: false,
callback: null,
no_items_html: '',
globalize_culture: (typeof navigator !== "undefined" && navigator !== null) && (navigator.browserLanguage || navigator.language || navigator.userLanguage),
globalize_fmt_datetime: 'f',
globalize_fmt_date: 'D',
globalize_fmt_time: 't',
globalize_fmt_monthday: 'M',
date_formatter: function(d, allday_p) {
var fmtstr;
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
if (allday_p) {
fmtstr = this.globalize_fmt_date;
} else {
fmtstr = this.globalize_fmt_datetime;
}
return Globalize.format(d, fmtstr);
} else {
if (allday_p) {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate()));
} else {
return "" + (d.getFullYear()) + "-" + (pad_zero(d.getMonth() + 1)) + "-" + (pad_zero(d.getDate())) + " " + (pad_zero(d.getHours())) + ":" + (pad_zero(d.getMinutes()));
}
}
},
daterange_formatter: function(sd, ed, allday_p) {
var endstr, ret;
ret = this.date_formatter(sd, allday_p);
if (allday_p) {
ed = new Date(ed.getTime() - 86400 * 1000);
}
endstr = '';
if (sd.getDate() !== ed.getDate() || sd.getMonth() !== ed.getMonth()) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_monthday);
} else {
endstr += "" + (pad_zero(ed.getMonth() + 1)) + "-" + (pad_zero(ed.getDate()));
}
}
if (!allday_p && (sd.getHours() !== ed.getHours() || sd.getMinutes() !== ed.getMinutes())) {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.format != null)) {
endstr += Globalize.format(ed, this.globalize_fmt_time);
} else {
endstr += " " + (pad_zero(ed.getHours())) + ":" + (pad_zero(ed.getMinutes()));
}
}
if (endstr) {
ret += " - " + endstr;
}
return ret;
}
};
function gCalFlow(target, opts) {
this.target = target;
target.addClass('gCalFlow');
if (target.children().size() > 0) {
log.debug("Target node has children, use target element as template.");
this.template = target;
}
this.update_opts(opts);
}
gCalFlow.prototype.update_opts = function(new_opts) {
log.debug("update_opts was called");
log.debug("old options:", this.opts);
this.opts = $.extend({}, this.opts, new_opts);
return log.debug("new options:", this.opts);
};
gCalFlow.prototype.gcal_url = function() {
if (!this.opts.calid && !this.opts.feed_url) {
log.error("Option calid and feed_url are missing. Abort URL generation");
this.target.text("Error: You need to set 'calid' or 'feed_url' option.");
throw "gCalFlow: calid and feed_url missing";
}
if (this.opts.feed_url) {
return this.opts.feed_url;
} else if (this.opts.mode === 'updates') {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=lastmodified&sortorder=descending";
} else {
return "https://www.google.com/calendar/feeds/" + this.opts.calid + "/public/full?alt=json-in-script&max-results=" + this.opts.maxitem + "&orderby=starttime&futureevents=true&sortorder=ascending&singleevents=true";
}
};
gCalFlow.prototype.fetch = function() {
var success_handler,
_this = this;
log.debug("Starting ajax call for " + (this.gcal_url()));
success_handler = function(data) {
log.debug("Ajax call success. Response data:", data);
return _this.render_data(data, _this);
};
return $.ajax({
success: success_handler,
dataType: "jsonp",
url: this.gcal_url()
});
};
gCalFlow.prototype.parse_date = function(dstr) {
var day, hour, m, min, mon, offset, ret, sec, year;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})$/)) {
return new Date(parseInt(m[1], 10), parseInt(m[2], 10) - 1, parseInt(m[3], 10), 0, 0, 0);
}
offset = (new Date()).getTimezoneOffset() * 60 * 1000;
year = mon = day = null;
hour = min = sec = 0;
if (m = dstr.match(/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|([+-])(\d{2}):(\d{2}))$/)) {
year = parseInt(m[1], 10);
mon = parseInt(m[2], 10);
day = parseInt(m[3], 10);
hour = parseInt(m[4], 10);
min = parseInt(m[5], 10);
sec = parseInt(m[6], 10);
if (m[7] !== "Z") {
offset += (m[8] === "+" ? 1 : -1) * (parseInt(m[9], 10) * 60 + parseInt(m[10], 10)) * 1000 * 60;
}
} else {
log.warn("Time parse error! Unknown time pattern: " + dstr);
return new Date(1970, 1, 1, 0, 0, 0);
}
log.debug("time parse (gap to local): " + offset);
ret = new Date(new Date(year, mon - 1, day, hour, min, sec).getTime() - offset);
log.debug("time parse: " + dstr + " -> ", ret);
return ret;
};
gCalFlow.prototype.render_data = function(data) {
var ci, desc_body_method, ed, ent, et, etf, feed, ic, it, items, link, sd, st, stf, t, titlelink, _i, _len, _ref1, _ref2;
log.debug("start rendering for data:", data);
feed = data.feed;
t = this.template.clone();
titlelink = (_ref1 = this.opts.titlelink) != null ? _ref1 : "http://www.google.com/calendar/embed?src=" + this.opts.calid;
if (this.opts.link_title) {
t.find('.gcf-title').html($("<a />").attr({
target: this.opts.link_target,
href: titlelink
}).text(feed.title.$t));
} else {
t.find('.gcf-title').text(feed.title.$t);
}
t.find('.gcf-link').attr({
target: this.opts.link_target,
href: titlelink
});
t.find('.gcf-last-update').html(this.opts.date_formatter(this.parse_date(feed.updated.$t)));
it = t.find('.gcf-item-block');
it.detach();
it = $(it[0]);
log.debug("item block template:", it);
items = $();
log.debug("render entries:", feed.entry);
if (this.opts.item_description_as_html) {
desc_body_method = 'html';
} else {
desc_body_method = 'text';
}
if ((feed.entry != null) && feed.entry.length > 0) {
_ref2 = feed.entry.slice(0, +this.opts.maxitem + 1 || 9e9);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
ent = _ref2[_i];
log.debug("formatting entry:", ent);
ci = it.clone();
if (ent.gd$when) {
st = ent.gd$when[0].startTime;
sd = this.parse_date(st);
stf = this.opts.date_formatter(sd, st.indexOf(':') < 0);
ci.find('.gcf-item-date').html(stf);
ci.find('.gcf-item-start-date').html(stf);
et = ent.gd$when[0].endTime;
ed = this.parse_date(et);
etf = this.opts.date_formatter(ed, et.indexOf(':') < 0);
ci.find('.gcf-item-end-date').html(etf);
ci.find('.gcf-item-daterange').html(this.opts.daterange_formatter(sd, ed, st.indexOf(':') < 0));
}
ci.find('.gcf-item-update-date').html(this.opts.date_formatter(this.parse_date(ent.updated.$t), false));
link = $('<a />').attr({
target: this.opts.link_target,
href: ent.link[0].href
});
if (this.opts.link_item_title) {
ci.find('.gcf-item-title').html(link.clone().text(ent.title.$t));
} else {
ci.find('.gcf-item-title').text(ent.title.$t);
}
if (this.opts.link_item_description) {
ci.find('.gcf-item-description').html(link.clone()[desc_body_method](ent.content.$t));
} else {
ci.find('.gcf-item-description')[desc_body_method](ent.content.$t);
}
ci.find('.gcf-item-location').text(ent.gd$where[0].valueString);
ci.find('.gcf-item-link').attr({
href: ent.link[0].href
});
log.debug("formatted item entry:", ci[0]);
items.push(ci[0]);
}
} else {
items = $('<div class=".gcf-no-items"></div>').html(this.opts.no_items_html);
}
log.debug("formatted item entry array:", items);
ic = t.find('.gcf-item-container-block');
log.debug("item container element:", ic);
ic.html(items);
this.target.html(t.html());
this.bind_scroll();
if (this.opts.callback) {
return this.opts.callback.apply(this.target);
}
};
gCalFlow.prototype.bind_scroll = function() {
var scroll_children, scroll_container, scroll_timer, scroller, state;
scroll_container = this.target.find('.gcf-item-container-block');
scroll_children = scroll_container.find(".gcf-item-block");
log.debug("scroll container:", scroll_container);
if (!this.opts.auto_scroll || scroll_container.size() < 1 || scroll_children.size() < 2) {
return;
}
state = {
idx: 0
};
scroller = function() {
var scroll_to;
log.debug("current scroll position:", scroll_container.scrollTop());
log.debug("scroll capacity:", scroll_container[0].scrollHeight - scroll_container[0].clientHeight);
if (typeof scroll_children[state.idx] === 'undefined' || scroll_container.scrollTop() >= scroll_container[0].scrollHeight - scroll_container[0].clientHeight) {
log.debug("scroll to top");
state.idx = 0;
return scroll_container.animate({
scrollTop: scroll_children[0].offsetTop
});
} else {
scroll_to = scroll_children[state.idx].offsetTop;
log.debug("scroll to " + scroll_to + "px");
scroll_container.animate({
scrollTop: scroll_to
});
return state.idx += 1;
}
};
return scroll_timer = setInterval(scroller, this.opts.scroll_interval);
};
return gCalFlow;
})();
methods = {
init: function(opts) {
var data;
if (opts == null) {
opts = {};
}
data = this.data('gCalFlow');
if (!data) {
return this.data('gCalFlow', {
target: this,
obj: new gCalFlow(this, opts)
});
}
},
destroy: function() {
var data;
data = this.data('gCalFlow');
data.obj.target = null;
$(window).unbind('.gCalFlow');
data.gCalFlow.remove();
return this.removeData('gCalFlow');
},
render: function() {
if ((typeof Globalize !== "undefined" && Globalize !== null) && (Globalize.culture != null)) {
Globalize.culture(this.data('gCalFlow').obj.opts.globalize_culture);
}
return this.data('gCalFlow').obj.fetch();
}
};
$.fn.gCalFlow = function(method) {
var orig_args;
orig_args = arguments;
if (typeof method === 'object' || !method) {
return this.each(function() {
methods.init.apply($(this), orig_args);
return methods.render.apply($(this), orig_args);
});
} else if (methods[method]) {
return this.each(function() {
return methods[method].apply($(this), Array.prototype.slice.call(orig_args, 1));
});
} else if (method === 'version') {
return "1.2.5";
} else {
return $.error("Method " + method + " does not exist on jQuery.gCalFlow");
}
};
}).call(this);
HTML:
<div id="gcf-custom-template">
<div class="gcf-item-container-block">
<div class="gcf-item-block">
<div class="gcf-item-header-block">
<div class="gcf-item-title-block">
<div style="float: left; width 250px;"><a class="gcf-item-link"><span class="gcf-item-daterange">2012-02-01 09:00</span>:</a></div>
<div style="float: left; width 250px;"><a class="gcf-item-location">1-877-346-9707 w 55586#</a></div>
<div style="float: left; width 250px;"><strong><a class="gcf-item-title">Item Title of Your event</a></strong></div>
</div>
</div>
</div>
</div>
</div>
Script Call:
<script type="text/javascript">
var $ = jQuery;
$(function() {
$('#gcf-custom-template').gCalFlow({
calid: '4t0m1c.w07f#gmail.com',
maxitem: 50,
mode: 'updates',
date_formatter: function(d, allday_p) { return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getYear().toString().substr(-2) }
});
});
</script>
Here is my solution to a similar problem, using moment.js for date formatting, markupjs for templating, and jQuery for general making life easier.
// a markup.js pipe which calls on moment.js for formatting
Mark.pipes.moment = function (date, format) {
return moment(new Date(date)).format(format);
};
// a markup.js pipe that tests if two dates are in the same month (difference between "1st-2nd december" and "30 november - 2 december")
Mark.pipes.diffmonth = function (date1, date2) {
moment1 = moment(new Date(date1));
moment2 = moment(new Date(date2));
var ret= moment1.month()!=moment2.month();
return ret;
};
// a markup.js pipe to filter an array
Mark.pipes.sift = function (arr, prop, val) {
return $.grep(arr,function(item) {
return item[prop] == val;
});
};
$(document).ready(loadCalendarData);
// this is a google calendar public full json feed (to have complete date and location information)
calendarURL = "http://www.google.com/calendar/feeds/6vv7tct80gv5tblahm5sg0vsos#group.calendar.google.com/public/full?alt=json-in-script&orderby=starttime&singleevents=true&sortorder=ascending&futureevents=true&callback=?";
function loadCalendarData() {
$.getJSON( calendarURL, applyTemplate);
}
function applyTemplate(cal_data) {
// format dates in french
moment.lang("fr");
// take cal_data, a google calendar json full feed. and extract VCALENDAR fields. Also extract a type field that distinguishes single day events from multiple day events.
var events = $.map(cal_data["feed"]["entry"], function (event) {
var url= $.grep(event["link"], function(link) {
return link["rel"]=="related";
});
return {
"summary": event["title"]["$t"],
"dtstart": event["gd$when"][0]["startTime"],
"dtend": event["gd$when"][0]["endTime"],
"url": url[0]?url[0]["href"]:"",
"location": event["gd$where"][0]["valueString"],
"type": (moment.duration(new Date(event["gd$when"][0]["endTime"])-new Date(event["gd$when"][0]["startTime"])).as("hours")<18)?"single":"multi"
};
});
// summary with url link if exists
Mark.includes.linked_summary = "{{if url}}<a href='{{url}}'>{{/if}}{{summary}}{{if url}}</a>{{/if}}";
// location in brackets if exists
Mark.includes.optional_location = "{{if location}} ({{location}}){{/if}}"
// separate list of evenings and multiple day/weeked events
var template =
"Les soirées à venir :<ul>{{events|sift>type>single}}"+
"<li>{{dtstart|moment>dddd|capcase}} {{dtstart|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>"+
"<br>"+
"Les stages et weekends à venir (2013/2014):<ul>{{events|sift>type>multi}}"+
"<li>{{dtstart|moment>D}}{{if dtstart|diffmonth>`dtend`}}{{dtstart|moment>/M}}{{/if}}-{{dtend|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
"{{/events}}</ul>";
$("#web").html(Mark.up(template, {"events":events}));
}
Hi i am using phone gap technology for blackberry development . i want to call soap based xml .when i run html page on internet explore web service response will come but when i run in simulator or device no response will come.Please help.thanks in advance .i used java script.
/*
Javascript "SOAP Client" library
#version: 2.1 - 2006.09.08
#author: Matteo Casati - http://www.guru4.net/
*/
var arr = new Array();
var arrayIndex;
arrayIndex = 0;
function SOAPClientParameters()
{
var _pl = new Array();
this.add = function(name, value)
{
_pl[name] = value;
return this;
}
this.toXml = function()
{
var xml = "";
for(var p in _pl)
xml += "<" + p + ">" + SOAPClientParameters._serialize(_pl[p]) + "</" + p + ">";
return xml;
}
}
SOAPClientParameters._serialize = function(o)
{
var s = "";
switch(typeof(o))
{
case "string":
s += o.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); break;
case "number":
case "boolean":
s += o.toString(); break;
case "object":
// Date
if(o.constructor.toString().indexOf("function Date()") > -1)
{
var year = o.getFullYear().toString();
var month = (o.getMonth() + 1).toString(); month = (month.length == 1) ? "0" + month : month;
var date = o.getDate().toString(); date = (date.length == 1) ? "0" + date : date;
var hours = o.getHours().toString(); hours = (hours.length == 1) ? "0" + hours : hours;
var minutes = o.getMinutes().toString(); minutes = (minutes.length == 1) ? "0" + minutes : minutes;
var seconds = o.getSeconds().toString(); seconds = (seconds.length == 1) ? "0" + seconds : seconds;
var milliseconds = o.getMilliseconds().toString();
var tzminutes = Math.abs(o.getTimezoneOffset());
var tzhours = 0;
while(tzminutes >= 60)
{
tzhours++;
tzminutes -= 60;
}
tzminutes = (tzminutes.toString().length == 1) ? "0" + tzminutes.toString() : tzminutes.toString();
tzhours = (tzhours.toString().length == 1) ? "0" + tzhours.toString() : tzhours.toString();
var timezone = ((o.getTimezoneOffset() < 0) ? "+" : "-") + tzhours + ":" + tzminutes;
s += year + "-" + month + "-" + date + "T" + hours + ":" + minutes + ":" + seconds + "." + milliseconds + timezone;
}
// Array
else if(o.constructor.toString().indexOf("function Array()") > -1)
{
for(var p in o)
{
if(!isNaN(p)) // linear array
{
(/function\s+(\w*)\s*\(/ig).exec(o[p].constructor.toString());
var type = RegExp.$1;
switch(type)
{
case "":
type = typeof(o[p]);
case "String":
type = "string"; break;
case "Number":
type = "int"; break;
case "Boolean":
type = "bool"; break;
case "Date":
type = "DateTime"; break;
}
s += "<" + type + ">" + SOAPClientParameters._serialize(o[p]) + "</" + type + ">"
}
else // associative array
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">"
}
}
// Object or custom function
else
for(var p in o)
s += "<" + p + ">" + SOAPClientParameters._serialize(o[p]) + "</" + p + ">";
break;
default:
throw new Error(500, "SOAPClientParameters: type '" + typeof(o) + "' is not supported");
}
return s;
}
function SOAPClient() {}
SOAPClient.invoke = function(url, method, parameters, async, callback)
{
if(async)
SOAPClient._loadWsdl(url, method, parameters, async, callback);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function(url, method, parameters, async, callback)
{
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if(wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp);
}
SOAPClient._onLoadWsdl = function(url, method, parameters, async, callback, req)
{
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl);
}
SOAPClient._sendSoapRequest = function(url, method, parameters, async, callback, wsdl)
{
// get namespace
var ns = (wsdl.documentElement.attributes["targetNamespace"] + "" == "undefined") ? wsdl.documentElement.attributes.getNamedItem("targetNamespace").nodeValue : wsdl.documentElement.attributes["targetNamespace"].value;
alert(ns);
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", soapaction);
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if(async)
{
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
}
xmlHttp.send(sr);
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp);
}
SOAPClient._onSendSoapRequest = function(method, async, callback, wsdl, req)
{
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Response");
alert("ND " +nd);
if(nd.length == 0)
{
if(req.responseXML.getElementsByTagName("faultcode").length > 0)
{
if(async || callback)
o = new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
else
throw new Error(500, req.responseXML.getElementsByTagName("faultstring")[0].childNodes[0].nodeValue);
} else {
}
}
else{
o = SOAPClient._soapresult2object(nd[0], wsdl);
}
if(callback){
callback(arr);
}
if(!async)
return o;
}
SOAPClient._soapresult2object = function(node, wsdl)
{
var wsdlTypes = SOAPClient._getTypesFromWsdl(wsdl);
return SOAPClient._node2object(node, wsdlTypes);
}
SOAPClient._node2object = function(node, wsdlTypes)
{
if(node == null)
{
return null;
}
// text node
if(node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdlTypes);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdlTypes);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdlTypes).toLowerCase().indexOf("arrayof") != -1;
// object node
if(!isarray)
{
var obj = null;
if(node.hasChildNodes())
{
obj = new Object();
for(var i = 0; i < node.childNodes.length ; i++)
{
var p = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
if((node.childNodes[i].nodeName.toLowerCase().indexOf("Return") == -1) && (node.childNodes[i].nodeName.toLowerCase().indexOf("Response") == -1))
{
obj[node.childNodes[i].nodeName] = p;
}
}
arr[arrayIndex++] = obj;
}
return obj;
}
// list node
else
{
//create node ref
var l = new Array();
for(var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdlTypes);
return l;
}
return null;
}
SOAPClient._extractValue = function(node, wsdlTypes)
{
var value = node.nodeValue;
switch(SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdlTypes).toLowerCase())
{
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if(value == null)
return null;
else
{
value = value + "";
value = value.substring(0, (value.lastIndexOf(".") == -1 ? value.length : value.lastIndexOf(".")));
value = value.replace(/T/gi," ");
value = value.replace(/-/gi,"/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypesFromWsdl = function(wsdl)
{
var wsdlTypes = new Array();
// IE
var ell = wsdl.getElementsByTagName("s:element");
var useNamedItem = true;
// MOZ
if(ell.length == 0)
{
ell = wsdl.getElementsByTagName("element");
useNamedItem = false;
}
for(var i = 0; i < ell.length; i++)
{
if(useNamedItem)
{
if(ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("type") != null)
wsdlTypes[ell[i].attributes.getNamedItem("name").nodeValue] = ell[i].attributes.getNamedItem("type").nodeValue;
}
else
{
if(ell[i].attributes["name"] != null && ell[i].attributes["type"] != null)
wsdlTypes[ell[i].attributes["name"].value] = ell[i].attributes["type"].value;
}
}
return wsdlTypes;
}
SOAPClient._getTypeFromWsdl = function(elementname, wsdlTypes)
{
var type = wsdlTypes[elementname] + "";
return (type == "undefined") ? "" : type;
}
// private: utils
SOAPClient._getElementsByTagName = function(document, tagName)
{
try
{
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\""+ tagName +"\"]");
}
catch (ex) {}
// old XML parser support
return document.getElementsByTagName(tagName);
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function()
{
try
{
if(window.XMLHttpRequest)
{
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if(req.readyState == null)
{
req.readyState = 1;
req.addEventListener("load",
function()
{
req.readyState = 4;
if(typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
if(window.ActiveXObject)
return new ActiveXObject(SOAPClient._getXmlHttpProgID());
}
catch (ex) {}
throw new Error("Your browser does not support XmlHttp objects");
}
SOAPClient._getXmlHttpProgID = function()
{
if(SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for(var i = 0; i < progids.length; i++)
{
try
{
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
}
xmlParsingDataReturn=function(){
return arr;
}
As a WebWorks app, you are required to whitelist any external domains you will be accessing through your app. Since this works on a computer's browser but not on an actual device or on the simulator, it may be an issue with the config file. See the PhoneGap site for more info on whitelisting.