Event Source Polyfill, send parameters - javascript

I am using Event Source Pollyfill : https://github.com/Yaffle/EventSource/blob/master/eventsource.js
I noticed that this pollyfill send a unique code like r=5743466970371525. I also want to send a parameter for every request/retry.
I did this:
user_time = 1407805878;
var sse = new EventSource('server.php?user_time='+user_time);
sse.addEventListener('message',function(e){
var data = e.data;
var obj = JSON.parse(data);
// here I have updated user_time from responce
user_time = obj['time'];
console.log(obj);
},false);
But after changing value of user_time from response, still old time is sent.
I hope I need need to override EventSource url from prototype ?
I tried this to update EventSource url:
user_time = 1407805878;
var sse = new EventSource('server.php?user_time='+user_time);
sse.addEventListener('message',function(e){
var data = e.data;
var obj = JSON.parse(data);
// here I tried to update URLe
sse.url = 'server.php?user_time='+obj['time']
user_time = obj['time'];
console.log(obj);
},false);
So, please help me to send a custom parameter. The pollyfill I am using does this, but I cant figure out how to ?
Thanks

Related

Override post requests

I have this code that I put in my console:
XMLHttpRequest.prototype.send = function(body) {
// modifies inputted request
newBody = JSON.parse(body);
newBody.points = 417;
// sends modified request
this.realSend(JSON.stringify(newBody));
}
It is supposed to make the points 417 every time it sends a request, but when I look at the request body, it still says the original amount of points. Any help?
Try to add an alert() or console.log() into your modified XMLHttpRequest.prototype.send to check if it actually works. There is a way to prevent this kind of modifications silently.
As others have noted, the error you are experiencing is hard to diagnose exactly without seeing how you created this.realSend.
However, this code will work:
const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (body) {
const newBody = JSON.parse(body);
newBody.points = 417;
send.call(this, JSON.stringify(newBody));
};
Note that instead of storing the original send method on XMLHttpRequest.prototype, I've kept in a separate variable and simply invoked it with the correct this value through send.call(). This seems like a cleaner implementation with less chance for conflicts with other code.
See this codesandbox for a working example.
If your function is not being called, possible fetch is used to make ajax requests.
So you can wrap both functions, like this
const send = XMLHttpRequest.prototype.send;
const _fetch = window.fetch;
XMLHttpRequest.prototype.send = function (body) {
const newBody = JSON.parse(body);
newBody.points = 417;
send.call(this, JSON.stringify(newBody));
};
window.fetch = function(url, options){
let newBody;
if(options.body) {
newBody = JSON.parse(options.body);
newBody.points = 417;
options.body = JSON.stringify(newBody);
}
_fetch.call(this, url, options);
}

Object doesn't support property or method 'getAll'

I am trying to implement service workers into my application, which I have managed to do in Chrome, Firefox and Safari but not completely in IE. So far I am able to create an object store and add data to it but when I call getAll() I get the following error:
SCRIPT438: Object doesn't support property or method 'getAll'
This is the code I am trying to run:
var docDB = indexedDB.open("docDB", 1);
docDB.onsuccess = function(event) {
var db = docDB.result;
var tx = db.transaction("documents", "readwrite");
var docStore = tx.objectStore("documents");
var docStoreRequest = docStore.getAll();
docStoreRequest.onsuccess = function(event) {
var rowHTML = '';
$.each( docStoreRequest.result, function( index, value ){
var id = $(this)[0].id;
});
};
Neither IE nor Edge support all of the IndexedDB spec. One of the missing things is getAll. Fortunately, there is a polyfill you can use.

How to update multiple fields in Firebase Web?

I have the following code where I want to update some simple values in my Firebase database using the JavaScript, Web SDK.
However, it doesn't run/update my database. What's wrong here?
var dbRef = firebase.database().ref().child('feeds').child(selectedFeed).child('audio');
var uid = dbRef.push().key;
var data = {
"downloadURL": uploadTask.snapshot.downloadURL,
"fileName": file.name,
"timeStamp": selectedDateUnix
};
var updates = {};
updates["mostRecentKey"] = uid;
updates[uid] = data;
dbRef.update(updates).then(function(){
//success
alert("Successfully Uploaded. This is now available to be listened to by your users.");
}).catch(function(error){
//failure
alert(error.message);
});
While it doesn't ever specify in the Firebase docs and actually I felt indicated it wasn't required; You MUST cast your data. For example:
This does not work. Directly accessing the variable.
var myNum = 10;
var data = {};
data["myNum"] = myNum;
This does work, but doesn't allow a dynamic use of a var.
var data = {};
data["myNum"] = 10;
Finally, this works and was my solution using a variable reference. Cast your data.
var myNum = 10;
var data = {};
data["myNum"] = Number(myNum);

How to pass variable to a new page using pop up window?

I have got a function which turning the Id of the clicked element into a variable, then a new window opens up with a new page. How can I access/use the variable on that new page?
var idToWrite = [];
$(function(){
$(".szlink div").bind("click", function(){
idToWrite.push($(this).attr("id"));
window.open("itemEncJS.html");
//do something
});
It is not safe and it is not meant to use plain html to process requests from urls.
However if you really want to do it, you can open the popup with the url with the values like this:
window.open("itemEncJS.html?name1=value1&name2=value2");
Then in the second page you will have to use regex to pick the value from url, something like this:
url = window.location.href;
nameValuePairs = url.match(/[\w]*=[\w]*/ig)
values = {}
nameValuePairs.forEach(function(pair){
nv = pair.split("=");
values[nv[0]] = nv[1];
})
Now you can use values to get your required values
e.g
val1 = values[name1]
val2 = values[name2]
you can use local storage:
on current page:
var storage = window.localStorage;
storage.setItem('id', id);
on the new page:
var storage = window.localStorage;
var id = storage.getItem('id');

How can I use an ajax request to fire Webservice calls in Javascript

I am currently working on some javascript that can be included in the header of surveys that use TrueSample, and will dynamically generate and fire Webservice calls for the survey. One of the requirements of Truesample is that after every page, it is sent the amount of time spend on that page, as well as some other arbitrary information generated in the beginning of the survey. I am trying to automate the every page web service call, so that I don't have to have hundreds of web services in every survey.
I am pretty far along, and have found some cool tricks to make this all work, but I am struggling with firing the webservice using javascript.
Here is what I have so far:
Qualtrics.SurveyEngine.addOnload(function()
{
var pageStart = new Date();
var beginning = pageStart.getTime();
// Necessary Variables
var account-id = parseInt("${e://Field/account-id}");
var passcode = parseInt("${e://Field/passcode}");
var survey-country = parseInt("${e://Field/survey-country}");
var end-client-id = parseInt("${e://Field/end-client-id}");
var page-exposure-duration;
var page-id = parseInt("${e://Field/pageID}");
var platform-id = parseInt("${e://Field/platform-id}");
var respondent-id = parseInt("${e://Field/respondent-id}");
var response-id = parseInt("${e://Field/response-id}");
var source-id = parseInt("${e://Field/source-id}");
var survey-id = parseInt("${e://Field/survey-id}");
var api-version = parseInt("${e://Field/api-version}");
//End Variables
var that = this;
that.hideNextButton();
var para = document.createElement("footnote");
var test = document.getElementById("Buttons");
var node = document.createElement('input');
var next = document.getElementById("NextButton");
node.id = "tsButton";
node.type = "button";
node.name = "tsButton";
node.value = " >> ";
node.onclick = function trueSample(){
var pageEnd = new Date();
var end = pageEnd.getTime();
var time = end - beginning;
window.alert(pageID + ", time spent on page = " + time);
Qualtrics.SurveyEngine.setEmbeddedData("pageID", pageID + 1);
new Ajax.Request('webserviceURL', {
parameters: {
account-id: account-id,
passcode: passcode,
survey-country: surveycountry,
end-client-id: end-client-id,
page-exposure-duration: time,
page-id: page-id,
platform-id: platform-id,
respondent-id: respondent-id,
response-id: response-id,
source-id: source-id,
survey-id: survey-id,
api-version: api-version}
});
that.clickNextButton();
};
para.appendChild(node);
test.insertBefore(para, next);
});
Does anyone have experience with firing webservice calls out of Javascript? And if so, do you have any ideas on how to finalize the ajax request and make it work? Or is there another(potentially better) method that I could use for these calls that would work? I understand that there is information on this on Stack Overflow, but I am having a hard time understanding how specific use cases apply to mine.
Also, please note that, while I would love to use JQuery, I am limited to vanilla Javascript, and Prototype.JS.
Using Traditional javascript XmlHttpRequest you can make an AJAX call. For a Webservice, we need couple of HTTP Headers. Like: SOAPAction, Content-Type, Accept. The values for these headers MUST be like below:
SOAPAction:""
Content-Type:text/xml
Accept:text/xml
So, additionally, your code should look something like this for making an AJAX call to the Webservice:
//Get XML Request Object
var request = new XMLHttpRequest();
// Define the URL
var url="http://your.end.point.url?wsdl";
//Define HTTP Method. Always POST for a Webservice
request.open("POST", url, true); // Remember that all the Webservice calls should be POST
//Setting Request Headers
request.setRequestHeader("SOAPAction", "\"\"");//Not sure of the escape sequence. The value should be "".
request.setRequestHeader("Accept","text/xml");
request.setRequestHeader("Content-Type","text/xml");
//Make your AJAX call
request.send(soap); // where soap is you SOAP Request Payload.
Parsing the response:
request.onreadystatechange=stateChanged;
function stateChanged()
{
if (request.status==200)
{
// Success. Parse the SOAP Response
}
if(request.status==500)
{
//Failure. Handle the SOAP Fault
}
}

Categories

Resources