I'm am strugling to get a webworker to load an XML file from the same domain on the side of my main page, any help would be greatly appreciated.
function readXML(){
var xhr = new XMLHttpRequest(); //Only for FF
xhr.open("GET","../db/pointer.xml",true);
xhr.send(null);
xhr.onreadystatechange = function(e){
if(xhr.status == 200 && xhr.readyState == 4){
//Post back info to main page
postMessage(xhr.responseXML.getElementsByTagName("value").length);
}
}
When this runs in a script tag on the main page, i get a 3.
When running thru the WebWorker, FireBug gives me
hr.responseXML is null
postMessage(xhr.responseXML.getElementsByTagName("value").length);
In the FireBug console, GET Request responded with
<?xml version="1.0" encoding="UTF-8"?>
<root>
<value>A value</value>
<value>Another Value</value>
<value>A third Value</value>
</root>
So the response is correct but i cannot figure out where it's going wrong.
If i change responseXML to responseText the worker outputs
A value Another Value A third Value
Which is correct! why won't the script open it as an XML document?
UPDATE
function readXML(){
var xhr = new XMLHttpRequest(); //Only for FF
xhr.open("GET","../db/pointer.xml",false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xhr.overrideMimeType('text/xml');
xhr.send(null);
xhr.onreadystatechange = function(e){
if(xhr.status == 200 && xhr.readyState == 4){
//Post back info to main page
postMessage(xhr.responseXML.getElementsByTagName("value").length);
}
}
When setRequestHeader & overrideMimeType is changed, the onreadystatechange never fires, doesn't matter if status and readyState are there or not, it won't run. If i remove the onreadystatechange completely and just run xhr.responseXML, i get the null error again.
I still get the correct XML in as response in the console, is this a webworker issue instead of a httprequest problem? Getting desperate here :)
index.html http://www.axlonline.se/worker/index.html
worker.js http://www.axlonline.se/worker/worker.js
According to the standard, Web workers can have not have access to any type of DOM manipulation.
The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification.
responseXML and channel properties are always null from an ajax request as the parsing of the XML is a DOM API. No matter the request and response headers there will be no way of getting requestXML unless you manually parse it.
Had the same Problem. Apparently XML parsing is not possible in webworkers.
I used sax.js to parse a XML on web worker.
https://github.com/isaacs/sax-js
this is basicly my parser.
function xmlParser(strict){
this.parser = sax.parser(strict, {lowercase:true});
}
xmlParser.prototype.parseFile = function(file, callback){
var _this = this;
$.ajax.get({
cache: false,
url: file,
dataType: "xml",
success: function(data){
var dom = _this.parseText(data.text);
callback( dom );
},
error: function(data){
}
});
}
xmlParser.prototype.parseText = function(xlmText){
var dom = undefined;
var activeNode = dom;
this.parser.onerror = function (e) { };
this.parser.onend = function () {};
this.parser.ontext = function (t) {
if(activeNode != undefined)
activeNode.Text = t;
};
this.parser.onopentag = function (node) {
var node = new xmlNode(node.name, activeNode, node.attributes, dom);
if(dom === undefined){
dom = node;
activeNode = node;
}else{
activeNode.Children.push(node);
activeNode = node;
}
};
this.parser.onclosetag = function (node) {
activeNode = activeNode.Parent;
};
this.parser.write(xlmText).close();
return dom;
}
xmlNode enables a jquery like handling of the tree.
function xmlFilterResult(){
this.length = 0;
}
xmlFilterResult.prototype.push = function(element){
this[this.length++] = element;
}
xmlFilterResult.prototype.attr = function(atribute){
if(this.length == 0)
return '';
return this[0].Attributes[atribute];
}
xmlFilterResult.prototype.text = function(atribute){
if(this.length == 0)
return '';
return this[0].Text;
}
xmlFilterResult.prototype.children = function(search, result){
if(result == undefined)
result = new xmlFilterResult();
if(search == undefined){
for(var i = 0; i < this.length; i++){
this[i].children(search, result);
}
}else{
this.find(search, true, result);
}
return result;
}
xmlFilterResult.prototype.find = function(search, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
if(search.charAt(0) == '.')
return this.findAttr('class', search.substring(1), nonrecursive, result);
else if(search.charAt(0) == '#')
return this.findAttr('id', search.substring(1), nonrecursive, result);
else
return this.findName(search, nonrecursive, result);
}
xmlFilterResult.prototype.findAttr = function(attr, value, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
var child;
for(var i = 0; i < this.length; i++){
child = this[i];
child.findAttr(attr, value, nonrecursive, result);
}
return result
}
xmlFilterResult.prototype.findName = function(name, nonrecursive, result){
if(result == undefined)
result = new xmlFilterResult();
var child;
for(var i = 0; i < this.length; i++){
child = this[i];
child.findName(name, nonrecursive, result);
}
return result
}
// xmlFilterResult.prototype.findID = function(id, nonrecursive){
// var child, result = new xmlFilterResult();
// for(var i = 0; i < this.length; i++){
// child = this[i];
// child.findID(id, nonrecursive, result);
// }
// return result
// }
function xmlNode(name, parent, atributes, root){
this.Name = name;
this.Children = [];
this.Parent = parent;
this.Attributes = atributes;
this.Document = root;
this.Text = '';
}
xmlNode.prototype.attr = function(atribute){
return this.Attributes[atribute];
}
xmlNode.prototype.text = function(atribute){
return this.Text;
}
xmlNode.prototype.children = function(search, result){
if(result == undefined)
result = new xmlFilterResult();
if(search == undefined){
for(i in this.Children)
result.push(this.Children[i]);
}else{
return this.find(search, true, result);
}
return result;
}
xmlNode.prototype.find = function(search, nonrecursive, result){
if(search.charAt(0) == '.')
return this.findAttr('class', search.substring(1), nonrecursive, result);
else if(search.charAt(0) == '#')
return this.findAttr('id', search.substring(1), nonrecursive, result);
else
return this.findName(search, nonrecursive, result);
}
xmlNode.prototype.findAttr = function(attr, value, nonrecursive, result){
var child, i;
if(result == undefined)
result = new xmlFilterResult();
for(i in this.Children){
child = this.Children[i];
if(child.Attributes[attr] == value)
result.push(child);
if(!nonrecursive)
child.findAttr(attr, value, nonrecursive, result);
}
return result
}
xmlNode.prototype.findName = function(name, nonrecursive, result){
var child, i;
if(result == undefined)
result = new xmlFilterResult();
for(i in this.Children){
child = this.Children[i];
if(child.Name == name){
result.push(child);
}
if(!nonrecursive)
child.findName(name, nonrecursive, result);
}
return result
}
Its nothing special but you get the idea of that to do.
You just need to set the content-type header to text/xml on the server side.
responseXML is null if the document that you're requesting isn't XML. Specifically, the content-type should be one of text/html, text/xml, application/xml, or something that ends in +xml. See the spec.
Also, see: responseXML is null and responseXML always null.
And a side note: since web workers are inherently asynchronous, you don't need to set the async flag to true in your open call.
Related
I have created a custom GET and POST function in javascript to handle my AJAX requests. When I try to make a call, fail callback is executed first and then the done callback. The response from AJAX is a valid JSON string and I do not understand why this is happening. Only done callback must be executed if the response is valid JSON.
get('ajax/autocomplete.php', {q: q}, function(data) {
//done, executed second
}, aww());//Error, executed first
function get() {
var data,
done,
fail,
done_index = null,
str = '',
ajax = new XMLHttpRequest(),
url = arguments[0];
for(var i=0; i<arguments.length; i++) {
if(typeof arguments[i] == 'object') {
data = arguments[i];
for(var key in data) {
if(str != "") str += "&";
str += key + "=" + encodeURIComponent(data[key]);
}
if(str != '') url += '?';
} else if(typeof arguments[i] == 'function') {
if(!done_index) {
done = arguments[i];
done_index = i;
}
if(i != done_index) {
fail = arguments[i];
}
}
}
ajax.onreadystatechange = function() {
console.log(ajax.readyState, ajax.status);
if(ajax.readyState === XMLHttpRequest.DONE && ajax.status === 200) {
var response = ajax.responseText;//treat empty response as valid JSON
if(response.length == 0) response = '""';
try {
var json = JSON.parse(response);
return (done) ? done(json) : false;
} catch(e) {
console.log(e);
return (fail) ? fail() : false;
}
}
};
ajax.open('get', url + str);
ajax.send();
}
You're calling the aww() function in the argument list to get(), because you have parentheses after it. You should just pass a reference to the function. It should be:
get('ajax/autocomplete.php', {q: q}, function(data) {
}, aww);
I'm generating a series of variables in a loop (using JS), and I'm assigning them an .id and a .name based on the current index. At each loop I'm sending a request to the server using jQuery.post()method, but the returning response is just an empty variable.
Here's the code:
JavaScript
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
$(document).ready(function(){
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
});
}
PHP
<?php
$index = $_POST['ind'];
$myVar = $_POST['myVarID'.$index];
echo $myVar;
?>
Response: Server response: ''
If I instead set a static index in JS code, getting rid of the loop, so for example:
var index = 0;
I get the expected result: Server response: myVarName0
Why is this happening? And how can I solve it?
Assuming the php file is in order. I use this:
function doThing(url) {
getRequest(
url,
doMe,
null
);
}
function doMe(responseText) {
var container = document.getElementById('hahaha');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
var thing = "script.php?" + url;
req.open("GET", thing, true);
req.send(null);
return req;
}
then use it like this:
doThing("myVarID="+myVar.id+"&i="+index);
also, you will have to change your PHP to something like this:
<?php
$index = $_GET['ind'];
$myVar = $_GET['myVarID'.$index];
echo $myVar;
?>
Obviously this code needs to be edited to suit your own needs
the function doMe is what to do when the webpage responds, in that example I changed the element with the id hahaha to the response text.
This won't win you any prizes but it'll get the job done.
Solution
It is working fine removing:
$(document).ready()
Working code
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
}
I'm trying to execute several pl/sql blocks in a Dynamic Action, with feedback to the end user with a modal dialog reporting the current satus.
Something like:
Processing Step 1...
/*Run pl/sql code for step 1*/
Processing Step 2...
/*Run pl/sql code for Step 2*/
and so on...
Both, the pl/sql and javascript code, run as intended but when I combined them on a Dynamic Action in the sequence:
1 - Execute Javascript
2 - Execute PL/SQL block /* With wait for result option checked*/
3 - Execute Javascript
4 - Execute PL/SQL block
The status dialog is not been shown, however the pl/sql blocks are completed without problems.
I realize that this must be something related to javascript not been multithreaded, so I've moved the pl/sql block to application processes and run them as ajax calls like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = get.get();
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = get.get();
}
closeStatusDialog();
}
But still, as before, the processes run fine but the dialog doesn't appear. Finally I added a setTimeOut function to each call, like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = setTimeOut(get.get(),500);
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = setTimeOut(get.get(),500);
}
closeStatusDialog();
}
But still nothing. What can I do to get this running as needed?.
I've checked the browser console and no exeptions are been thrown, likewise with the pl/sql blocks.
I've solved it, although the solution doesn't rely on dynamic actions, just javascript and applicacion processes. I'm posting this for anyone with a similar problem.
The htmldb_Get Javascript object is an oracle-apex wrapper for the XMLHttpRequest AJAX object. Poorly documented though.
I've found a copy of the code (at the bottom) and it turns out it has another function called GetAsync that allows to pass a function as a parameter to asign it to the onreadystatechange attribute on the XMLHttpRequest object, which will be executed each time the attribute readyState of the underlying XMLHttpRequest changes.
The function passed as a parameter can't have parameters on its own definition.
So, instead of calling get() on the htmldb_Get object you need to call GetAsync(someFunction)
With this solution in my case:
function something(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
get.GetAsync(someFunctionStep1);
}
function someFunctionStep1(){
if(p.readyState == 0){ /*p is the underlying XMLHttpRequest object*/
console.log("request not initialized");
updateStatus('Running Step 1');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
callStep2();
}
}
function callStep2(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
get.GetAsync(someFunctionStep2);
}
function someFunctionStep2(){
if(p.readyState == 0){
console.log("request not initialized");
updateStatus('Running Step 2');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
closeDialog();
}
}
Here's the htmldb_get definition, at the end is the GetAsync function
/*
str should be in the form of a valid f?p= syntax
*/
function htmldb_Get(obj,flow,req,page,instance,proc,queryString) {
//
// setup variables
//
this.obj = $x(obj); // object to put in the partial page
this.proc = proc != null ? proc : 'wwv_flow.show'; // proc to call
this.flow = flow != null ? flow : $x('pFlowId').value; // flowid
this.request = req != null ? req : ''; // request
this.page = page; // page
this.params = ''; // holder for params
this.response = ''; // holder for the response
this.base = null; // holder fot the base url
this.queryString = queryString!= null ? queryString : null ; // holder for passing in f? syntax
this.syncMode = false;
//
// declare methods
//
this.addParam = htmldb_Get_addParam;
this.add = htmldb_Get_addItem;
this.getPartial = htmldb_Get_trimPartialPage;
this.getFull = htmldb_Get_fullReturn;
this.get = htmldb_Get_getData;
this.url = htmldb_Get_getUrl;
this.escape = htmldb_Get_escape;
this.clear = htmldb_Get_clear;
this.sync = htmldb_Get_sync;
this.setNode = setNode;
this.replaceNode = replaceNode
//
// setup the base url
//
var u = window.location.href.indexOf("?") > 0 ?
window.location.href.substring(0,window.location.href.indexOf("?"))
: window.location.href;
this.base = u.substring(0,u.lastIndexOf("/"));
if ( this.proc == null || this.proc == "" )
this.proc = u.substring(u.lastIndexOf("/")+1);
this.base = this.base +"/" + this.proc;
//
// grab the instance form the page form
//
if ( instance == null || instance == "" ) {
var pageInstance = document.getElementById("pInstance");
if ( typeof(pageInstance) == 'object' ) {
this.instance = pageInstance.value;
}
} else {
this.instance = instance;
}
//
// finish setiing up the base url and params
//
if ( ! queryString ) {
this.addParam('p_request', this.request) ;
this.addParam('p_instance', this.instance);
this.addParam('p_flow_id', this.flow);
this.addParam('p_flow_step_id',this.page);
}
function setNode(id) {
this.node = html_GetElement(id);
}
function replaceNode(newNode){
var i=0;
for(i=this.node.childNodes.length-1;i>=0;i--){
this.node.removeChild(this.node.childNodes[i]);
}
this.node.appendChild(newNode);
}
}
function htmldb_Get_sync(s){
this.syncMode=s;
}
function htmldb_Get_clear(val){
this.addParam('p_clear_cache',val);
}
//
// return the queryString
//
function htmldb_Get_getUrl(){
return this.queryString == null ? this.base +'?'+ this.params : this.queryString;
}
function htmldb_Get_escape(val){
// force to be a string
val = val + "";
val = val.replace(/\%/g, "%25");
val = val.replace(/\+/g, "%2B");
val = val.replace(/\ /g, "%20");
val = val.replace(/\./g, "%2E");
val = val.replace(/\*/g, "%2A");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\\/g, "%5C");
val = val.replace(/\//g, "%2F");
val = val.replace(/\>/g, "%3E");
val = val.replace(/\</g, "%3C");
val = val.replace(/\{/g, "%7B");
val = val.replace(/\}/g, "%7D");
val = val.replace(/\~/g, "%7E");
val = val.replace(/\[/g, "%5B");
val = val.replace(/\]/g, "%5D");
val = val.replace(/\`/g, "%60");
val = val.replace(/\;/g, "%3B");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\#/g, "%40");
val = val.replace(/\&/g, "%26");
val = val.replace(/\#/g, "%23");
val = val.replace(/\|/g, "%7C");
val = val.replace(/\^/g, "%5E");
val = val.replace(/\:/g, "%3A");
val = val.replace(/\=/g, "%3D");
val = val.replace(/\$/g, "%24");
//val = val.replace(/\"/g, "%22");
return val;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addParam(name,val){
if ( this.params == '' )
this.params = name + '='+ ( val != null ? this.escape(val) : '' );
else
//this.params = this.params + '&'+ name + '='+ ( val != null ? val : '' );
this.params = this.params + '&'+ name + '='+ ( val != null ? this.escape(val) : '' );
return;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addItem(name,value){
this.addParam('p_arg_names',name);
this.addParam('p_arg_values',value);
}
//
// funtion strips out the PPR sections and returns that
//
function htmldb_Get_trimPartialPage(startTag,endTag,obj) {
setTimeout(html_processing,1);
if (obj) {this.obj = $x(obj);}
if (!startTag){startTag = '<!--START-->'};
if (!endTag){endTag = '<!--END-->'};
var start = this.response.indexOf(startTag);
var part;
if ( start >0 ) {
this.response = this.response.substring(start+startTag.length);
var end = this.response.indexOf(endTag);
this.response = this.response.substring(0,end);
}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.value = this.response;
}
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.innerHTML = this.response;
}
}
}
//window.status = 'Done'
setTimeout(html_Doneprocessing,1);
return this.response;
}
var gResult = null;
var gNode = null
function htmldb_get_WriteResult(){
if(gNode && ( gNode.nodeName == 'INPUT' || gNode.nodeName == 'TEXTAREA')){
gNode.value = gResult;
}else{
gNode.innerHTML = gResult;
}
gResult = null;
gNode = null;
return;
}
//
// function return the full response
//
function htmldb_Get_fullReturn(obj) {
setTimeout(html_processing,1);
if (obj) { this.obj = html_GetElement(obj);}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
this.obj.value = this.response;
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,10);
}else{
this.obj.innerHTML = this.response;
}
}
}
setTimeout(html_Doneprocessing,1);
return this.response;
}
//
// Perform the actual get from the server
//
function htmldb_Get_getData(mode,startTag,endTag){
html_processing();
var p;
try {
p = new XMLHttpRequest();
} catch (e) {
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, this.syncMode);
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
this.response = p.responseText;
if ( this.node )
this.replaceNode(p.responseXML);
if ( mode == null || mode =='PPR' ) {
return this.getPartial(startTag,endTag);
} if ( mode == "XML" ) {
setTimeout(html_Doneprocessing,1);
return p.responseXML;
} else {
return this.getFull();
}
} catch (e) {
setTimeout(html_Doneprocessing,1);
return;
}
}
function html_Doneprocessing(){
document.body.style.cursor="default";
}
function html_processing(){
document.body.style.cursor="wait";
}
/*
this adds better aysnc functionality
to the htmldb_Get object
pVar is the function that you want to call when the xmlhttp state changes
in the function specified by pVar the xmlhttp object can be referenced by the variable p
*/
htmldb_Get.prototype.GetAsync = function(pVar){
try{
p = new XMLHttpRequest();
}catch(e){
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, true);
if(p) {
p.onreadystatechange = pVar;
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
return p;
}
}catch(e){
return false;
}
}
/* PDF OUTPUT */
/*Gets PDF src XML */
function htmldb_ExternalPost(pThis,pRegion,pPostUrl){
var pURL = 'f?p='+html_GetElement('pFlowId').value+':'+html_GetElement('pFlowStepId').value+':'+html_GetElement('pInstance').value+':FLOW_FOP_OUTPUT_R'+pRegion
document.body.innerHTML = document.body.innerHTML + '<div style="display:none;" id="dbaseSecondForm"><form id="xmlFormPost" action="' + pPostUrl + '?ie=.pdf" method="post" target="pdf"><textarea name="vXML" id="vXML" style="width:500px;height:500px;"></textarea></form></div>';
var l_El = html_GetElement('vXML');
var get = new htmldb_Get(l_El,null,null,null,null,'f',pURL.substring(2));
get.get();
get = null;
setTimeout('html_GetElement("xmlFormPost").submit()',10);
return;
}
function $xml_Control(pThis){
this.xsl_string = '<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html"/><xsl:param name="xpath" /><xsl:template match="/"><xsl:copy-of select="//*[#id=$xpath]"/></xsl:template></xsl:stylesheet>';
if(document.all){
this.xsl_object = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
this.xsl_object.async=false;
this.xsl_object.loadXML(this.xsl_string)
tmp = new ActiveXObject("Msxml2.XSLTemplate.3.0");
tmp.stylesheet = this.xsl_object;
this.xsl_processor = tmp.createProcessor();
}else{
this.xsl_object = (new DOMParser()).parseFromString(this.xsl_string, "text/xml");
this.xsl_processor = (new XSLTProcessor());
this.xsl_processor.importStylesheet(this.xsl_object);
this.ownerDocument = document.implementation.createDocument("", "test", null);
}
this.xml = pThis;
this.CloneAndPlace = _CloneAndPlace;
return
function _CloneAndPlace(pThis,pThat,pText){
var lThat = $x(pThat);
if(document.all){
this.xsl_processor.addParameter("xpath", pThis);
this.xsl_processor.input = this.xml;
this.xsl_processor.transform;
var newFragment = this.xsl_processor.output;
}else{
this.xsl_processor.setParameter(null, "xpath", pThis);
var newFragment = this.xsl_processor.transformToFragment(this.xml,this.ownerDocument);
}
if(lThat){
if(document.all){
lThat.innerHTML='';
lThat.innerHTML=newFragment;
}else{
lThat.innerHTML='';
lThat.appendChild(newFragment);
}
/*
in IE newFragment will be a string
in FF newFragment will be a dome Node (more useful)
*/
return newFragment;
}
}
}
I wrote my 1st application in Node.js with MongoDB and I came across the situation where I need to have 2 db.collection.update statements depending on an IF/ELSE condition.
I am trying to return back the operation details in a resJSON JS object but seems like callback is executing before the db.collection.update statements are completed and the default value of resJSON is getting back in response each time.
detail code:
var url = require('url');
var fs = require('fs');
var async = require('async');
var passwordGen = require('../../lib/passwordGen');
var http = require("http");
var server = http.createServer();
server.on('request', request);
server.listen(8080,'127.0.0.1');
function request(request, response) {
var userData = '';
request.on('data', function(data)
{
userData += data;
});
request.on('end', function()
{
async.auto({
allProcess: function(callback){
var resJSON = {'inserted':0,'disabled':0,'error':''};
var jsonData = JSON.parse(userData);
if(jsonData.length > 0){
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/test_db", function(err,db){
if(err) { return console.dir(err); }
var collection = db.collection('users');
var arrDisableRec = [];
for(i=0;i<jsonData.length;i++){
var action = jsonData[i]['action'].toLowerCase();
if(action == 'disable'){
arrDisableRec.push(jsonData[i]['email']);
}else{
var date = new Date();
var obj = {
'createdISO':date,
'created':date,
'updated':date,
'updatedISO':date,
'email':jsonData[i]['email'],
'firstName':jsonData[i]['firstname'],
'lastName':jsonData[i]['lastname'],
'password':passwordGen.getPassword(),
'enabled':true,
'active':true,
'downloaded':true,
'defaultServings':2,
'name':''
};
collection.update(
{'email':jsonData[i]['email']},
{$setOnInsert:obj},
{upsert: true},
function(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
}
);
}
if(arrDisableRec.length > 0){
collection.update(
{'email':{$in:arrDisableRec}},
{$set:{'enabled':false}},
{multi:true},
function(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
}
);
}
}
});
}
callback(resJSON);
}
},function(resJSON){
response.writeHead(200,{
'Content-Type': 'text/json'
});
response.end(JSON.stringify(resJSON)); //replies back with default resJSON only.
});
});
}
Any suggestions/directions please?
Thanks
You have to call the callback at then end of the callback chain.
For example
console.log(resJSON); //shows correct values
callback(null, resJSON);
you will have to make sure that every callback chain end point calls the callback. To handle the for loop you will have to have a mechanism to join all the end points of all the async calls done inside the for loop.
for example
if(err) {
return callback(err);
}
notice that I used the function callback(err, res) standard node prototype instead of your function callback(res)
better yet, use an async flow library like async or a promise library like bluebird
This is a counter solution for your issue. It should solve your case for now. Try reading async library. It will be very useful for later.
var counter = 0;
function commoncallback(err,numberAffected,rawResponse) {
if(typeof numberAffected.result.upserted != 'undefined'){
resJSON['inserted'] = resJSON['inserted'] + numberAffected.result.upserted.length;
}
if(typeof numberAffected.result.nModified != 'undefined'){
resJSON['disabled'] = resJSON['disabled'] + parseInt(numberAffected.result.nModified);
}
if(typeof numberAffected.result.writeError != 'undefined'){
resJSON['error'] ='Error Code:'+(numberAffected.result.writeError.code)+', '+numberAffected.result.writeError.errmsg;
}
console.log(resJSON); //shows correct values
counter --;
if(counter == 0) callback(resJSON); //call your main call back here
}
for (i=0; i<jsonData.length; i++) {
if(firstCase) {
counter ++;
collection.update({'email':{$in:arrDisableRec}},
{$set:{'enabled':false}},
{multi:true},commoncallback);
} else {
//another update action
counter++;
}
}
I've a small Greasemonkey script that doesn't include any random part, but its results change with each page reload.
I'm a noob and I'm probably doing something wrong, but I don't know what. I hope you'll be able to help me.
The code is too large and too poorly written to be reproduced here, so I'll try to sum up my situation:
I have a list of links which have href=javascript:void(0) and onclick=f(link_id).
f(x) makes an XML HTTP request to the server, and returns the link address.
My script is meant to precompute f(x) and change the href value when the page loads.
I have a function wait() that waits for the page to load, then a function findLinks() that gets the nodes that are to be changed (with xpath).
Then a function sendRequest() that sends the xhr to the server. And, finally handleRequest() that asynchronously (r.onreadystatechange) retrieves the response, and sets the nodes previously found.
Do you see anything wrong with this idea?
Using a network analyzer, I can see that the request is always sent fine, and the response also.
Sometimes the href value is changed, but sometimes for some links it isn't and remains javascript:void(0).
I really don't see why it works only half the time...
function getUrlParameterFromString(urlString, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(urlString);
if (results == null) {
return "";
} else {
return results[1];
}
}
function getUrlParameter(name) {
return getUrlParameterFromString(window.location.href, name);
}
function wait() {
var findPattern = "//a";
var resultLinks = document.evaluate(findPattern, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
if (resultLinks == null || resultLinks.snapshotLength == 0) {
return setTimeout(_wait, 100);
} else {
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
sendRequest(linkId, node);
}
}
}
function sendRequest(linkId, nodeToModify) {
window.XMLHttpRequest ? r = new XMLHttpRequest : window.ActiveXObject && (r = new ActiveXObject("Microsoft.XMLHTTP"));
if (r) {
r.open("POST", "some_url", !0);
r.onreadystatechange = function () {
handleRequest(nodeToModify, linkId, r);
}
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.send(linkId);
}
}
function handleRequest(nodeToModify, num, r) {
if (r.readyState == 4) {
if (r.status == 200) {
console.log('handleRequest() used');
var a = r.responseText;
if (a == null || a.length < 10) {
sendRequest(num, nodeToModify);
} else {
var url = unescape((getUrlParameterFromString(a, "url")).replace(/\+/g, " "));
nodeToModify.setAttribute('href', url);
nodeToModify.setAttribute('onclick', "");
}
} else {
alert("An error occurred: " + r.statusText)
}
}
}
wait();
It looks like that script will change exactly 1 link. Look-up "closures"; this loop:
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
sendRequest(linkId, node);
}
needs a closure so that sendRequest() gets the correct values. Otherwise, only the last link will be modified.
Try:
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
//-- Create a closure so that sendRequest gets the correct values.
( function (linkId, node) {
sendRequest (linkId, node);
}
)(linkId, node);
}