How to send data to Zoho from wordpress via Javascript - javascript

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.

Related

Javascript RangeError on website proxy RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]

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);
}
}

instafeed.js not working because of CORS policy

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!

How can i set customize Form in add event of wdCalender?

i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>

Uncaught TypeError: Cannot read property 'options' of null

I cannot figure out why I keep getting this error:
Uncaught TypeError: Cannot read property 'options' of null
getFSREPlist
(anonymous function)
The error is referencing this line of code (21):
document.getElementById(elementidupdate).options.length=0;
What is weird is that it was working prior to this new google map api I just put on. Also, it is pulling the country code "1" and putting it in the drop down, but not the province code "19".
Here is the on page script:
getFSREPlist('1', 'fsrep-search-province', 'CountryID', '19');getFSREPlist('19', 'fsrep-search-city', 'ProvinceID', '3'); request.send(null);
Here is the full file:
function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
this.onLoading = function () {};
this.onLoaded = function () {};
this.onInteractive = function () {};
this.onCompletion = function () {};
this.onError = function () {};
this.onFail = function () {};
};
this.reset = function () {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function () {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function (name, value) {
this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function (string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++) {
urlVars = varArray[i].split("=");
if (true == encode) {
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function (urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring) {
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function () {
eval(this.response);
}
this.runAJAX = function (urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) {}
}
this.xmlhttp.onreadystatechange = function () {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
var ajax = new Array();
function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
var FSREPID = sel.options[sel.selectedIndex].value;
} else {
var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}
function ElementUpdate(index, elementidupdate) {
var obj = document.getElementById(elementidupdate);
eval(ajax[index].response);
}
You should call getFSREPlist when DOM is loaded. I ran
document.getElementById('fsrep-search-province').options.length=0
from chrome´s console. while page was still loading and caused that same error.
http://i.imgur.com/GBFizq1.png

Not getting response on simulator when i call web service using java script

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.

Categories