I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.
For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.
Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".
var last_params = "";
var autosave_time = 61000;
var autosave_fail_check = 5;
var max_autosave_fail_check = 5;
var response_text = "";
function autosave() {
var autosave_button_name = "save_button";
var form_action = document.getElementById("formS").action;
var form_data = document.getElementById("formS");
var all_inputs = form_data.getElementsByTagName("input");
var all_textareas = form_data.getElementsByTagName("textarea");
var params = "";
// Check all inputs for data
for (var i = 0; i < all_inputs.length; i++) {
var current_item = all_inputs[i];
if (current_item.type != "button" && current_item.type != "submit") {
if (current_item.type != "checkbox") {
params += current_item.name + "=" + current_item.value + "&";
} else {
params += current_item.name + "=" + current_item.checked + "&";
}
}
}
// check all textareas for data
for (var i = 0; i < all_textareas.length; i++) {
var current_item = all_textareas[i];
params += current_item.name + "=" + current_item.value + "&";
}
params += "autosave=1";
if (params == last_params) {
setTimeout(autosave, autosave_time);
return;
} else {
last_params = params;
}
// Setup time
var time = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
time = hours + ":" + minutes + ":" + seconds;
if(hours > 11){
time = time + "PM";
} else {
time = time + "AM";
}
var status = "[]";
// **************************************************
var http;
try {
// Gecko-based browsers, Safari, and Opera.
http = new XMLHttpRequest();
} catch(e) {
try {
// For Internet Explorer.
http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
document.getElementById(autosave_button_name).value = "Autosave NOT Available";
http = false;
}
}
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
autosave_fail_check = max_autosave_fail_check; // reset the fail check
}
status = " [" + http.readyState + " / " + http.status + "] ";
}
if (autosave_fail_check <= 0) {
if (autosave_fail_check == 0) {
document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
//alert("Autosave has FAILED! Please check your connection!");
}
autosave_fail_check = -1;
} else {
autosave_fail_check--;
}
var url = form_action;
http.open("POST", url, true); // async set to false to prevent moving on without saving
http.setRequestHeader("Content-type", "multipart/form-data");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(last_params);
response_text = http.responseText;
if (autosave_fail_check >= 0) {
document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
} else {
autosave_fail_check = -1;
}
setTimeout(autosave, autosave_time);
} // end function autosave()
Related
I am currently trying to run 2 separate XMLHTTPRequests in dynamics CRM Javascript to retrieve data from 2 different entities and run code depending on what is retrieved..
I've done my best to try and edit some names for security reasons, but the premise is the same.
My main problem is that the first run of the XMLHTTPRequest (the RA Banner) works fine, but then the second run (the Status Banner) the Readystate that is returned is 2 and stopping.
function FormBanners(formContext) {
//Clear the existing banners
formContext.ui.clearFormNotification("Notif1");
formContext.ui.clearFormNotification("Notif2");
//Get the customer/rep
var customer = formContext.getAttribute("customerid").getValue();
var rep = formContext.getAttribute("representative").getValue();
var contact;
//use the rep if there is one else use the customer
if (rep != null) {
contact = rep;
}
else if (customer!= null) {
contact = customer;
}
//Get the account
var account = formContext.getAttribute("accountfield").getValue();
//As there is a requirement for 2 XMLHTTPRequests we have to queue them
var requestURLs = new Array();
//There will always be a customers or rep on the form
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/contacts?$select=new_RA,new_SC,new_VC,new_PR&$filter=contactid eq " + contact[0].id + "", true);
//there may not be an account
if (account) {
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?$select=_new_statusLookup_value&$filter=accountid eq " + account[0].id + "", true);
}
var current = 0;
function getURL(url) {
var req = new XMLHttpRequest();
req.open("GET", requestURLs[current]);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(req.response);
// Creation of the RA Banner
if (current == 0) {
var RA = result.value[0]["new_RA#OData.Community.Display.V1.FormattedValue"];
var SC = result.value[0]["new_SC#OData.Community.Display.V1.FormattedValue"];
var VC = result.value[0]["new_VC#OData.Community.Display.V1.FormattedValue"];
var PR = result.value[0]["new_PR#OData.Community.Display.V1.FormattedValue"];
var Notif = "";
//Only create a notification if any of the above contain "Yes"
if (RA == "Yes" || SC == "Yes" || VC == "Yes" || PR == "Yes") { Notif = "The Customer/Rep has:" }
if (RA == "Yes") { Notif = Notif + " RA,"; }
if (SC == "Yes") { Notif = Notif + " SC,"}
if (VC == "Yes") { Notif = Notif + " VC,"}
if (PR == "Yes") { Notif = Notif + " PR."}
if (Notif != "") {
formContext.ui.setFormNotification(Notif, "INFO", "Notif1");
}
}
//Creation of the Status Banner
else if (current == 1) {
status = results.value[i]["_new_statusLookup_value"];
if (status) {
if (status[0].name != "Open")
var Notif = "The status for the organisation on this case is " + status[0].name + ".";
formContext.ui.setFormNotification(Notif, "INFO", "Notif2");
}
}
++current;
if (current < requestURLs.length) {
getURL(requestURLs[current]);
}
} else {
Xrm.Utility.alertDialog(req.statusText);
}
}
}; req.send();
}
getURL(requestURLs[current]);
}
Can anyone help me out?
So in my example I had made many mistakes. Taking Arun's advice I separated the function out, which made debugging far easier.. it instead was not failing on the XMLHTTP Request because that worked fine, but firefox was crashing when debugging.
So my issues were that I was in the second part:
Used the value of i for results (i was no longer defined)
Getting the "_new_statusLookup_value" would only provide the guid of the lookup I would instead want "_new_statusLookup_value#OData.Community.Display.V1.FormattedValue"
Lets not ignore the fact that because I had copied and pasted many iterations of this code that I was also using "results" instead of "result".
Many little mistakes.. but it happens! Thanks for the help, just goes to show.. typos are our downfall!
I wrote a script in JS that will retrieve the traffic source of the user and store that value in a cookie.
For all but three pages this works. If the user's landing page is for example www.example.com/example1, www.example.com/example2 or www.example.com/example3 the cookie gets stored on those pages only. I do not see see it in developer tools on chrome but when I write document.cookie I do see the cookie I created. I also see it in settings.
But if I were to navigate to another page it doesn't get stored.
It works fine on all other pages, the user enters on the landing page and the cookie stays stored during the whole session. Except on the above pages.
The hostname is the same for all pages.
Any ideas?
var source = trafficSource();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
var source = document.referrer;
}
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function checkCookie() {
var verifyCookie = getCookie("Traffic Source Cookie");
if (verifyCookie != null ){
//alert("there is a cookie");
return "";
}else{
setCookie("Traffic Source Cookie", source, 30);
//alert("new cookie made");
}
}
checkCookie();
var trafficSourceValue = getCookie("Traffic Source Cookie"); // delete if doesnt work
//dataLayer.push( "Cookie Traffic Source is " +getCookie("Traffic Source Cookie"));
function trafficSource(trafficType){
var trafficType;
//set traffic sources to variables
/*var sourceSearchEngine = searchEngine();
var sourceSocialNetwork = socialNetwork();
var sourcePaidSearch = paidSearch(); */
// get what kind of referrer
var trafficReferrer = document.referrer;
var trafficURL = document.URL;
if(trafficURL.indexOf("gclid") > -1) {
trafficType = paidSearch();
//alert("paidSearch google");
} else if (trafficURL.indexOf("bing") >-1 &&(trafficURL.indexOf("ppc")> -1) || (trafficURL.indexOf("cpc") >-1)){
trafficType = paidSearch();
//alert("paidSearch bing");
}
else if((trafficReferrer.indexOf("plus.url.google.com")<= 0) && trafficReferrer.indexOf("google")>-1 || trafficReferrer.indexOf("bing")>-1 || trafficReferrer.indexOf("baidu") >-1 || trafficReferrer.indexOf("yahoo") > -1 && (trafficURL.indexOf("ppc") < 0)){
trafficType = searchEngine();
//alert("searchEngine");
//(trafficReferrer.indexOf("facebook","googleplus", "twitter", "t.co/", "linkedin", "pinterest","reddit","disqus","blogspot.co.uk") >-1
} else if ((trafficReferrer.indexOf("facebook")>-1) || (trafficReferrer.indexOf("plus.url.google.com")>-1) || (trafficReferrer.indexOf("t.co/")>-1) || (trafficReferrer.indexOf("linkedin")>-1) || (trafficReferrer.indexOf("reddit")>-1) || (trafficReferrer.indexOf("disqus")>-1) || (trafficReferrer.indexOf("blogspot.co.uk")>-1) || (trafficReferrer.indexOf("t.umblr")>-1)) {
trafficType = socialNetwork();
//alert("socialNetwork");
} else if (trafficReferrer.indexOf("")>-0){
trafficType = directSource();
//alert("direct");
}else if (trafficURL.indexOf("display") >-1 || trafficURL.indexOf("Display") >-1){
trafficType = display();
//alert("display");
}else if (trafficReferrer === "" || trafficReferrer === null){
trafficType = "Direct";
}else {
//var hostnameReturn = hostname.split("www.");
var returnReferrer = document.referrer.match(/https?:\/\/([^\/]*)(?:\/|$)/i)[1].replace(/www\./, "");
// do I need this snippet
trafficType = returnReferrer + "/Referral" ;
//alert("Hostname Referral");
}
//Return the trafficType which is the function that will get source
return trafficType;
// alert("trafficType");
}
//setCookie("trafficSource",1,30)
//search engine source
function searchEngine (referrer){
var search = document.referrer;
var bing = "bing";
var google ="google";
var yahoo = "yahoo";
var ask = "ask";
var msn = "msn";
var baidu = "baidu";
var referrer;
if (search.indexOf(bing)> -1){
//alert(bing);
referrer = bing + " organic";
} else if (search.indexOf(yahoo)>-1){
// alert(bing);
referrer = yahoo + " organic";
} else if (search.indexOf(ask)>-1){
referrer = ask + " organic";
} else if (search.indexOf(msn)>-1){
// alert(bing);
referrer = msn + " organic";
} else if (search.indexOf(baidu)>-1){
// alert(baidu);
referrer = baidu + " organic";
}
else{
// alert(google);
referrer = google + " organic";
}
return referrer;
// alert("Search Engine: " + referrer);
}
//search social network
function socialNetwork (referrer){
var search = document.referrer;
var facebook ="facebook";
var twitter = "twitter";
var googlePlus = "google plus";
var googlePlus2 = "plus.url.google.com";
var pinterest ="pinterest";
var linkedin = "linkedin";
var tumblr = "t.umblr";
var reddit = "reddit";
//var beforeItsNews ="news";
var disquis = "disqus";
var blogger = "blogspot.co.uk";
//var StumbleUpon = "StumbleUpon";
var referrer;
if(search.indexOf(facebook)> -1){
// alert(facebook);
referrer = "Social/ " + facebook;
}else if (search.indexOf(twitter)> -1 || search.indexOf("t.co/") >-1){
// alert(twitter);
referrer = "Social/ "+ twitter;
}else if (search.indexOf(pinterest)> -1){
//alert(pinterest);
referrer = "Social/ "+ pinterest;
}else if (search.indexOf(linkedin) >- 1){
//alert(linkedin);
referrer = linkedin;
}else if (search.indexOf(googlePlus) >-1 || search.indexOf(googlePlus2) >-1){
// alert(googlePlus);
referrer = "Social/ "+ googlePlus;
}else if (search.indexOf(tumblr) >-1){
// alert(googlePlus);
referrer ="Social/ "+ "tumblr";
}else if (search.indexOf(reddit) >-1){
// alert(googlePlus);
referrer = "Social/ " + reddit;
}else if (search.indexOf(disquis) >-1){
//alert(disquis);
referrer = "Social/ "+ disquis;
}else if (search.indexOf(blogger) >-1){
blogger ="Blogger";
//alert(blogger);
referrer = "Social/ "+ blogger;
}else{
// alert(document.referrer);
referrer = "Referral: " + document.referrer;
// alert("Check Cookie - Referrer");
}
return referrer;
// alert("Social Media Network: " + referrer)
}
// search for paid search
function paidSearch(referrer){
var paidCampaign = document.URL;
var campaignReferrer = document.referrer;
var referrer;
var googleAd = "gclid";
var justGoogle = "google";
var justBing = "ppc";
var bingAd = "Bing";
if (paidCampaign.indexOf(googleAd) >- 1 || campaignReferrer.indexOf(justGoogle) >-1){
googleAd = "Google/CPC ";
// alert(googleAd);
//referrer = paidCampaign; < original code but trying the code on the bottom>
referrer = googleAd;
// alert(referrer);
}
if (paidCampaign.indexOf(bingAd)>- 1 || paidCampaign.indexOf(justBing) >-1){
bingAd = "Bing/CPC ";
//alert(bingAd);
referrer = bingAd ;
}
return referrer;
// alert("The paid ad is: " + googleAd);
}
function directSource(referrer){
var directVistor = document.referrer;
if(directVistor ==="" || directVistor === null ){
referrer = "Direct";
//alert("Direct");
}
return referrer;
}
function display(referrer){
var displayURL = document.URL;
var referrer;
if(displayURL.indexOf("display") >- 1 || displayURL.indexOf("Display")>-1){
var returnDisplay = window.location.search.substring(1);
referrer = "Display: " + returnDisplay;
//alert(referrer);
return referrer;
}
}
// function urlSpilt(url){
// // return utm_source and utm_medium if iti has it.
// var url;
// var getURL = document.URL;
// //var testURL = "http://www.franciscoignacioquintana.com/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName";
// var getURL = getURL.split("utm_source");
// getURL = getURL[1].split("utm_source");
// url = getURL;
// return url;
// }
//http://www.currencies.co.uk/?utm_source=testSource&utm_medium=testMedium&utm_campaign=testName
function getQueryParam(par){
//var strURL = document.URL;#
var strURL = document.referrer;
var regParam = new RegExp("(?:\\?|&)" + par + "=([^&$]*)", "i");
var resExp = strURL.match(regParam);
if((typeof resExp == "object") && resExp && (resExp.length > 1)){
return resExp[1];
}
else{
return "";
}
}
//var hostname = window.location.hostname;
//var hostnameReturn = hostname.split("www.");
//var hostname2 = hostname.slice(4);
I use this code to upload files, and this code have a progressbar. The problem with this code is that it never send me to "upload.php" after it have uploaded the file, after it reach 100% on the progressbar. (It's not my code).
The code:
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
The whole script
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
var uploadingcanceld = "حدث خطأ أثناء تحميل الملف";
function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600))/60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {hr = "0" + hr; }
if (min < 10) {min = "0" + min;}
if (sec < 10) {sec = "0" + sec;}
if (hr) {hr = "00";}
return hr + ':' + min + ':' + sec;
};
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
function fileSelected() {
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('ufile').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e){
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // binding onload event
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
function startUploading() {
// cleanup all temp states
iPreviousBytesLoaded = 0;
$("#upload").animate({height:'75px'},350);
$("#loadingborders").fadeIn(1500);
$("#progress_percent").fadeIn(1500);
$("#upload_button").fadeOut(100);
$("#ufile").fadeOut(100);
document.getElementById('ufile').style.margin = '5px 0px -5px 0px';
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
document.getElementById('progress_percent').innerHTML = '';
var oProgress = document.getElementById('progress');
oProgress.style.display = 'block';
oProgress.style.width = '0px';
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
// set inner timer
oTimer = setInterval(doInnerUpdates, 300);
}
function doInnerUpdates() { // we will use this function to display upload speed
var iCB = iBytesUploaded;
var iDiff = iCB - iPreviousBytesLoaded;
// if nothing new loaded - exit
if (iDiff == 0)
return;
iPreviousBytesLoaded = iCB;
iDiff = iDiff * 2;
var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
var secondsRemaining = iBytesRem / iDiff;
// update speed info
var iSpeed = iDiff.toString() + 'B/s';
if (iDiff > 1024 * 1024) {
iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
} else if (iDiff > 1024) {
iSpeed = (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
}
document.getElementById('speed').innerHTML = iSpeed;
document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}
function uploadProgress(e) { // upload process in progress
if (e.lengthComputable) {
iBytesUploaded = e.loaded;
iBytesTotal = e.total;
var iPercentComplete = Math.round(e.loaded * 100 / e.total);
var iBytesTransfered = bytesToSize(iBytesUploaded);
document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
document.getElementById('b_transfered').innerHTML = iBytesTransfered;
if (iPercentComplete == 100) {
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = '<h1>Please wait...processing</h1>';
}
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadFinish(e) { // upload successfully finished
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = e.target.responseText;
document.getElementById('progress_percent').innerHTML = '100%';
document.getElementById('progress').style.width = '400px';
document.getElementById('filesize').innerHTML = sResultFileSize;
document.getElementById('remaining').innerHTML = '| 00:00:00';
clearInterval(oTimer);
}
function uploadError(e) { // upload error
$('#errormessage').slideUp('fast', function() {
$('#errormessage').html(uploadingcanceld);
$('#errormessage').slideDown('fast');
});
clearInterval(oTimer);
}
function uploadAbort(e) { // upload abort
clearInterval(oTimer);
}
XHR is a dynamic data call, it's not a document forwarding call, meaning the reason why we have XHR to begin with is so that we DON'T want to forward a client to another page to get new content into the page. So you might want to wait on the XHR to complete the process of sending the data, acquire the results of that transfer via XHR, and based on those results do as you want.
So in essence, you are creating a virtual document client/server transfer and handshake without having to forward the client, that of which is the role XHR was created to fulfill.
Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.
I have a some code to ajax upload . its send request to my servlet and all works fine. But code contains a progress bar what i no need. Can u help me delete lines what i no need?
Another question how to refresh DIV with my content after upload files? When i use this code to send parametrs to jsp page
$.post(
"deletePoly.jsp",
{ids:ch.toString()},
function(per){
$("#WRAPlist").load("listing.jsp");
}
);
Where i gonn put line
$("#WRAPlist").load("listing.jsp");
this is upload code
var req;
function ajaxFunction()
{
var url = "Upload_Servlet";
if (window.XMLHttpRequest) // Non-IE browsers
{
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject) // IE Browsers
{
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}
function processStateChange()
{
* State Description
* 0 The request is not initialized
* 1 The request has been set up
* 2 The request has been sent
* 3 The request is in process
* 4 The request is complete
if (req.readyState == 4)
{
if (req.status == 200) // OK response
{
var xml = req.responseXML;
// No need to iterate since there will only be one set of lines
var isNotFinished = xml.getElementsByTagName("finished")[0];
var myBytesRead = xml.getElementsByTagName("bytes_read")[0];
var myContentLength = xml.getElementsByTagName("content_length")[0];
var myPercent = xml.getElementsByTagName("percent_complete")[0];
// Check to see if it's even started yet
if ((isNotFinished == null) && (myPercent == null))
{
document.getElementById("initializing").style.visibility = "visible";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("initializing").style.visibility = "hidden";
document.getElementById("progressBarTable").style.visibility = "visible";
document.getElementById("percentCompleteTable").style.visibility = "visible";
document.getElementById("bytesRead").style.visibility = "visible";
myBytesRead = myBytesRead.firstChild.data;
myContentLength = myContentLength.firstChild.data;
if (myPercent != null) // It's started, get the status of the upload
{
myPercent = myPercent.firstChild.data;
document.getElementById("progressBar").style.width = myPercent + "%";
document.getElementById("bytesRead").innerHTML = myBytesRead + " of " +
myContentLength + " bytes read";
document.getElementById("percentComplete").innerHTML = myPercent + "%";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("bytesRead").style.visibility = "hidden";
document.getElementById("progressBar").style.width = "100%";
document.getElementById("percentComplete").innerHTML = "Done!";
}
}
}
else
{
alert(req.statusText);
}
}
}
remove these line of codes then it will not display progressbar..
document.getElementById("initializing").style.visibility = "hidden";
document.getElementById("progressBarTable").style.visibility = "visible";
document.getElementById("percentCompleteTable").style.visibility = "visible";
document.getElementById("bytesRead").style.visibility = "visible";
myBytesRead = myBytesRead.firstChild.data;
myContentLength = myContentLength.firstChild.data;
if (myPercent != null) // It's started, get the status of the upload
{
myPercent = myPercent.firstChild.data;
document.getElementById("progressBar").style.width = myPercent + "%";
document.getElementById("bytesRead").innerHTML = myBytesRead + " of " +
myContentLength + " bytes read";
document.getElementById("percentComplete").innerHTML = myPercent + "%";
// Sleep then call the function again
window.setTimeout("ajaxFunction();", 100);
}
else
{
document.getElementById("bytesRead").style.visibility = "hidden";
document.getElementById("progressBar").style.width = "100%";
document.getElementById("percentComplete").innerHTML = "Done!";
}