Reload a page with additional data - javascript

If I have the following:
http://www.domain.com/myscript?x1=v1&x2=v2
And I would like to reload this page with additional data {x3: v3, x4: v4}. What is the simple way to do without manipulating the original url?

Reload the page using window.location
var original_url = window.location;
window.location = original_url + "&x3=data3&x4=data4";
Edit: You can update values from url using this function:
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
You can use it:
var x1 = updateURLParameter(window.location.href, 'x1', 'updatedData1');
var url = updateURLParameter(x1, 'x2', 'updatedData2');
window.location = url;

Related

Filling QC Google forms with many pages using Google Sheet- Only Last line of code not working i.e. UrlFetchApp

I have learned how to automate google form filling using google sheet and app script. After many trial and error to apply the concept and automate it on simple google forms i have created, it worked absolutely fine.
But when I applied on the google form (which i seriously want to automate), everything works fine except the last line of code i.e. UrlFetchApp which brings google form link and data together and submit the form using "post" method but it's not working.
When i commented this line rest of the code executed without any error but this line is making my effort fail.
google form link for which i have created this code: https://docs.google.com/forms/d/e/1FAIpQLSc1uSOspwlen5Tcs0ccTxE4eia-scw3aVUwAsrVMdQBpk5ydA/viewform
function QC_form_fill() {
var wrkBk = SpreadsheetApp.getActiveSpreadsheet();
var wrkSht = wrkBk.getSheetByName("Qdata");
var formURL =""
var formData =""
var sdate = "";
var stime = "";
var mname = "";
var board = "";
var eclas = "";
var batch = "";
var slecture = "";
var sfaculty = "";
var ati1 = "";
var ta1 = "";
var ta2 = "";
var ta3 = "";
var sopen = "";
var stengage = "";
var teachpace = "";
var chtresp = "";
var tmmanmnt = "";
var vomod = "";
var sgrammar = "";
var qppt = "";
var fhndwrtng = "";
var drssup = "";
var lobjective = "";
var expstyl = "";
var sflow = "";
var cntnacc = "";
var demos = "";
var ati2 = "";
var poll = "";
var la = "";
var hw = "";
var prlfcd = "";
var sggstn = "";
var noOfRows = wrkSht.getRange("AI1").getDisplayValue();
for (i=2; i<=noOfRows; i++)
{
sdate =wrkSht.getRange("A"+i).getDisplayValue();
stime =wrkSht.getRange("B"+i).getDisplayValue();
mname =wrkSht.getRange("C"+i).getDisplayValue();
board =wrkSht.getRange("D"+i).getDisplayValue();
eclas =wrkSht.getRange("E"+i).getDisplayValue();
batch =wrkSht.getRange("F"+i).getDisplayValue();
slecture =wrkSht.getRange("G"+i).getDisplayValue();
sfaculty =wrkSht.getRange("H"+i).getDisplayValue();
ati1 =wrkSht.getRange("I"+i).getDisplayValue();
ta1 =wrkSht.getRange("J"+i).getDisplayValue();
ta2 =wrkSht.getRange("K"+i).getDisplayValue();
ta3 =wrkSht.getRange("L"+i).getDisplayValue();
sopen =wrkSht.getRange("M"+i).getDisplayValue();
stengage =wrkSht.getRange("N"+i).getDisplayValue();
teachpace =wrkSht.getRange("O"+i).getDisplayValue();
chtresp =wrkSht.getRange("P"+i).getDisplayValue();
tmmanmnt =wrkSht.getRange("Q"+i).getDisplayValue();
vomod =wrkSht.getRange("R"+i).getDisplayValue();
sgrammar =wrkSht.getRange("S"+i).getDisplayValue();
qppt =wrkSht.getRange("T"+i).getDisplayValue();
fhndwrtng =wrkSht.getRange("U"+i).getDisplayValue();
drssup =wrkSht.getRange("V"+i).getDisplayValue();
lobjective =wrkSht.getRange("W"+i).getDisplayValue();
expstyl =wrkSht.getRange("X"+i).getDisplayValue();
sflow =wrkSht.getRange("Y"+i).getDisplayValue();
cntnacc =wrkSht.getRange("Z"+i).getDisplayValue();
demos =wrkSht.getRange("AA"+i).getDisplayValue();
ati2 =wrkSht.getRange("AB"+i).getDisplayValue();
poll =wrkSht.getRange("AC"+i).getDisplayValue();
la =wrkSht.getRange("AD"+i).getDisplayValue();
hw =wrkSht.getRange("AE"+i).getDisplayValue();
prlfcd =wrkSht.getRange("AF"+i).getDisplayValue();
sggstn =wrkSht.getRange("AG"+i).getDisplayValue();
formURL ="https://docs.google.com/forms/d/e/1FAIpQLSc1uSOspwlen5Tcs0ccTxE4eia-scw3aVUwAsrVMdQBpk5ydA/formResponse?pageHistory=0,1"
formData= "&entry.1809185170=" + sdate + "&entry.772722605=" + stime + "&entry.1721230767=" + mname + "&entry.1024240207=" + board + "&entry.1132896225=" + eclas +"&entry.134507089="+ batch + "&entry.1349051916=" + slecture + "&entry.15763511=" +sfaculty + "&entry.1915124723=" + ati1 + "&entry.1154530333=" + ta1 + "&entry.1450881147=" + ta2 + "&entry.1627300385=" + ta3 + "&entry.928964249=" + sopen + "&entry.103830616=" + stengage + "&entry.1749915137=" + teachpace + "&entry.1879781398=" + chtresp + "&entry.1210552578=" + tmmanmnt + "&entry.1659325247=" + vomod + "&entry.377007890=" + sgrammar + "&entry.1207703694=" + qppt + "&entry.960993930=" + fhndwrtng + "&entry.343485399=" + drssup + "&entry.1988728268=" + lobjective + "&entry.1019203670=" + expstyl + "&entry.222077844=" + sflow + "&entry.465124407=" + cntnacc + "&entry.1299956408=" + demos + "&entry.956891355=" + ati2 + "&entry.60052266=" + poll + "&entry.125539625=" + la + "&entry.1193513376=" + hw + "&entry.705255491=" + prlfcd + "&entry.121026171=" +sggstn
var finalURL = formURL + formData
var options = {
"method" : "post"
};
UrlFetchApp.fetch(finalURL, options);
}
}

Converting rdl to pdf using javascript

I want to convert my rdl report to pdf using javascript. It will be really good if I can only use OpenReport() and convert the pdf file there because then I have to convert it into ppt. I am using CRM online.
here is my code.
function OpenReport() {
debugger;
var formType = Xrm.Page.ui.getFormType();
if(formType != 1){
Xrm.Page.ui.setFormNotification("Please wait while system is generating pdf...", "INFO", "pdfGen");
var rdlName = "KalorikBrandPresentationv4.rdl"; //Replace with your report name
var entityType = "10060"; //Replace
var entityGuid = Xrm.Page.data.entity.getId();
var recordId = entityGuid.replace("{","").replace("}","");
var reportGuid = "ea721b27-44a6-ea11-9688-005056ba540f"; //Replace with your report guid
var url = Xrm.Page.context.getClientUrl() + "/crmreports/viewer/viewer.aspx?action=run&context=records&helpID=" + rdlName + "&id=%7b" + reportGuid + "%7d&records=%7b" + recordId + "%7d&recordstype=" + entityType;
var responseSession = getReportingSession(reportGuid,rdlName,recordId);
convertResponseToPDF(responseSession,rdlName);
}
function convertResponseToPDF(responseSession,reportName) {
debugger;
var pth = encodeURI(Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?
ReportSession=" + responseSession[0]+"&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[1] +"&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF");
var base64PDFString;
var retrieveEntityReq = new XMLHttpRequest();
retrieveEntityReq.open("GET", pth, true);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.responseType = "arraybuffer";
retrieveEntityReq.onreadystatechange = function () {
if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200) {
var binary = "";
var bytes = new Uint8Array(this.response);
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
base64PDFString = btoa(binary);
console.log(base64PDFString);
createNotesAttachment(base64PDFString,reportName);
}
};
retrieveEntityReq.send();
}
Did you followed the code/steps mentioned here
I remembers I worked on 2016 online for downloading report as PDF. This shall help.
You might want to change code a bit.
function runReportToPrint() {
var invoicenumber = Xrm.Page.getAttribute("invoicenumber").getValue()
if (invoicenumber != null) {
invoicenumber = invoicenumber.substring(4, 9);
var params = getReportingSession();
var newPth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + params[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + params[1] + "&OpType=Export&FileName=" + invoicenumber + "&ContentDisposition=OnlyHtmlInline&Format=PDF";
window.open(newPth, "_self");
encodePdf(params);
} else {
alert("Invoice ID is Missing");
}
}
function getReportingSession() {
var recordId = Xrm.Page.data.entity.getId();
recordId = recordId.replace('{', '').replace('}', '');
var strParameterXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='invoice'><all-attributes /><filter type='and'><condition attribute='invoiceid' operator='eq' value='" + recordId + "' /> </filter></entity></fetch>";
var pth = Xrm.Page.context.getClientUrl() + "/CRMReports/rsviewer/QuirksReportViewer.aspx";
var retrieveEntityReq = new XMLHttpRequest();
retrieveEntityReq.open("POST", pth, false);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
retrieveEntityReq.send("id=%7B" + reportGuid + "%7D&uniquename=" + Xrm.Page.context.getOrgUniqueName() + "&iscustomreport=true&reportnameonsrs=&reportName=" + reportName + "&isScheduledReport=false&p:CRM_invoice=" + strParameterXML);
var x = retrieveEntityReq.responseText.lastIndexOf("ReportSession=");
var y = retrieveEntityReq.responseText.lastIndexOf("ControlID=");
var ret = new Array();
ret[0] = retrieveEntityReq.responseText.substr(x + 14, 24);
ret[1] = retrieveEntityReq.responseText.substr(x + 10, 32);
return ret;
}
function encodePdf(responseSession) {
var retrieveEntityReq = new XMLHttpRequest();
var pth = Xrm.Page.context.getClientUrl() + "/Reserved.ReportViewerWebControl.axd?ReportSession=" + responseSession[0] + "&Culture=1033&CultureOverrides=True&UICulture=1033&UICultureOverrides=True&ReportStack=1&ControlID=" + responseSession[1] + "&OpType=Export&FileName=Public&ContentDisposition=OnlyHtmlInline&Format=PDF";
retrieveEntityReq.open("GET", pth, true);
retrieveEntityReq.setRequestHeader("Accept", "*/*");
retrieveEntityReq.responseType = "arraybuffer";
retrieveEntityReq.onreadystatechange = function () {
if (retrieveEntityReq.readyState == 4 && retrieveEntityReq.status == 200) {
var binary = "";
var bytes = new Uint8Array(this.response);
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
var bdy = btoa(binary);
createNote(bdy);
}
};
retrieveEntityReq.send();
}
function createNote(data) {
var note = {};
var recordId = Xrm.Page.data.entity.getId();
recordId = recordId.replace('{', '').replace('}', '');
var invoicenumber = Xrm.Page.getAttribute("invoicenumber").getValue()
invoicenumber = invoicenumber.substring(4, 9);
var refInvoice = new Object();
refInvoice.LogicalName = "invoice";
refInvoice.Id = recordId;
note.ObjectId = refInvoice;
note.ObjectTypeCode = refInvoice.LogicalName;
note.Subject = "Invoice: " + invoicenumber;
note.MimeType = "application/pdf";
note.DocumentBody = data;
note.FileName = invoicenumber + ".pdf";
XrmServiceToolkit.Rest.Create(
note,
"AnnotationSet",
function (result) {
//Alert user
alert("Note Created");
//Refresh data so user sees newly created note
Xrm.Page.data.refresh(false);
},
function (error) {
alert(error.message);
},
true);
}

Replace Variable in URL onClick

Want to replace the varaible after 'sku=' in the src= using onClick, then reload the iframe.
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button id="smrone" onclick="smrclickone()">test1</button>
<button id="smrtwo" onclick="smrclicktwo()">test2</button>
<button id="smrthree" onclick="smrclickthree()">test3</button>
<script>
function('smrclickone') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-1')
};
function('smrclicktwo') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-2')
};
function('smrclickthree') {
document.getElementById('preview').src = document.getElementById('preview').src.replace('sku','100-3')
};
</script>
This is simpler:
var baseUrl = "//preview.domain.com/?month=May";
window.onload=function() {
document.querySelector(".smr-three").onclick=function(e) {
if (e.target.tagName=="BUTTON") {
document.getElementById('preview').src = baseUrl+"&sku="+this.getAttribute("data-sku");
}
}
}
using
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button type="button" id="smrone" data-sku="100-1">test1</button>
<button type="button" id="smrtwo" data-sku="100-2">test2</button>
<button type="button" id="smrthree" data-sku="100-3">test3</button>
</div>
Replace does not do what you think here. This function can be used to update GET parameters in a URL:
function updateURLParameter(url, param, paramVal) {
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
Use that on your URL the following way:
let preview = document.getElementById('preview')
function smrclickone() {
preview.src = updateURLParameter(preview.src, "sku", "100-1");
console.log(preview.src)
};
function smrclicktwo() {
preview.src = updateURLParameter(preview.src, "sku", "100-2");
console.log(preview.src)
};
function smrclickthree() {
preview.src = updateURLParameter(preview.src, "sku", "100-3");
console.log(preview.src)
};
function updateURLParameter(url, param, paramVal) {
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i = 0; i < tempArray.length; i++) {
if (tempArray[i].split('=')[0] != param) {
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
<iframe id="preview" src="//preview.domain.com/?sku=100-1&month=May"></iframe>
<div class="smr-three">
<button id="smrone" onclick="smrclickone()">test1</button>
<button id="smrtwo" onclick="smrclicktwo()">test2</button>
<button id="smrthree" onclick="smrclickthree()">test3</button>

Click and swap data using a javascript callback handler

var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}; requestWeather.send();
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
tempreture.innerHTML = tempString;
tempreture.addEventListener("click", function( ) {
var ftemp = "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.innerHTML = ftemp;
},false);
}
function changeTemp(temp){
var tp = temp * 1.8 + 32;
var cel =Math.round(tp);
return cel;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="temp" onclick="getTemp()"></a>
How do I use the click callback handler to swap text from a different string
I want to switch between Fahrenheit and Celsius when a user clicks an element.
This is what I have done so far:
function getTemp(data) {
var tempString = "";
var temp = data.main.temp;
tempreture.addEventListener("click", function( ) {
tempString += "<p class='weather'>" + temp + '℃' + "</p>";
},false)
tempString += "<p class='weather'>" + changeTemp(temp) + '° F' + "</p>";
tempreture.insertAdjacentHTML("beforeend", tempString);
}
function changeTemp(temp){
var tp = (temp - 32) * 5/9;
var cel =Math.round(tp);
return cel;
};
I have only tried this using pure javascript. It would be great if someone can give me a hint as to what I'm doing incorrectly.
var temp = data.main.temp;
The temp is where I got the data from and is passed down to the HTML. I have done the conversion, but I don't know how to pass it back from the conversion function.
ADD the temperature data are come from
var requestWeather = new XMLHttpRequest();
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=' + data.lat + '&lon=' + data.lon);
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
}
Edit I had tried the click function, now. however, I found same issues with the return back to old value after the click.
I recommend that you validate the data that the API returns.
var tempreture = document.getElementById("temp")
var requestWeather = new XMLHttpRequest();
// global cache
var currentTemp,
currentUnit;
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getTemp(weatherData);
};
requestWeather.send();
function getTemp(data) {
currentTemp = typeof data === 'object' ? data.main.temp : null; // save new value in global cache
currentUnit = 'celcius';
tempreture.innerHTML = currentTemp + '℃';
}
tempreture.addEventListener("click", function() {
tempreture.innerHTML = changeTemp();
}, false);
function changeTemp() {
if(currentUnit === 'celcius') {
var tp = currentTemp * 1.8 + 32;
var fh = Math.round(tp);
currentUnit = 'fahrenheit';
return fh + '° F';
} else {
currentUnit = 'celcius';
return currentTemp + '℃';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="temp" class='weather'></span>

Overwrite existing URL parameter value with new

I want this code to replace an existing URL parameter "aspid", but what it does is adding an another id on the existing one. Can anyone help?
$(document).ready(function() {
function GetUrlValue(VarSearch) {
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for (var i = 0; i < VariableArray.length; i++) {
var KeyValuePair = VariableArray[i].split('=');
if (KeyValuePair[0] == VarSearch) {
return KeyValuePair[1];
}
}
}
var asid = GetUrlValue('aspid');
var campaign = GetUrlValue('utm_campaign');
if (asid != undefined) {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&aspid=" + asid : "?aspid=" + asid);
});
}
});
You need to call this function on every a:
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
And call the function like so:
updateURLParameter(window.location.href, 'paramName', 'Value')
complete code be like :
...
$("a").attr('href', function(i, h) {
if(h){
return updateURLParameter(h, 'aspid', asid);
}
});
...

Categories