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);
Related
EDIT: I have added the response from OMDB
{Response: "False", Error: "Invalid API key!"}
Error: "Invalid API key!"
Response: "False"
I am new to web development and I am trying to build a chrome extension that displays imdb scores on netflix. I am using the OMDB API to do this. At first I got the following error:
"Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint ''. This request has been blocked; the content must be served over HTTPS.",
however I just changed the "http" in the url to "https" and it went away. However, now I am getting a 401 error, which I think means my access is being denied.
This is a picture of the full error
Here is the code for the extension
Manifest file:
{
"manifest_version": 2,
"name": "1_ratings_netflix",
"version": "0.1",
"description": "Display imdb ratings on netflix",
"content_scripts": [
{
"matches": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
],
"js": ["content.js"]
}
],
"icons": { "16": "icon16.png", "48":"icon48.png"},
"permissions": [
"https://www.netflix.com/*", "https://www.omdbapi.com/*"
]
}
Content File:
function fetchMovieNameYear() {
var synopsis = document.querySelectorAll('.jawBone .jawbone-title-link');
if (synopsis === null) {
return;
}
var logoElement = document.querySelectorAll('.jawBone .jawbone-title-link .title');
if (logoElement.length === 0)
return;
logoElement = logoElement[logoElement.length - 1];
var title = logoElement.textContent;
if (title === "")
title = logoElement.querySelector(".logo").getAttribute("alt");
var titleElement = document.querySelectorAll('.jawBone .jawbone-title-link .title .text').textContent;
var yearElement = document.querySelectorAll('.jawBone .jawbone-overview-info .meta .year');
if (yearElement.length === 0)
return;
var year = yearElement[yearElement.length - 1].textContent;
var divId = getDivId(title, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var existingImdbRating = window.sessionStorage.getItem(title + ":" + year);
if ((existingImdbRating !== "undefined") && (existingImdbRating !== null)) {
addIMDBRating(existingImdbRating, title, year);
} else {
makeRequestAndAddRating(title, year)
}
};
function addIMDBRating(imdbMetaData, name, year) {
var divId = getDivId(name, year);
var divEl = document.getElementById(divId);
if (divEl && (divEl.offsetWidth || divEl.offsetHeight || divEl.getClientRects().length)) {
return;
}
var synopsises = document.querySelectorAll('.jawBone .synopsis');
if (synopsises.length) {
var synopsis = synopsises[synopsises.length - 1];
var div = document.createElement('div');
var imdbRatingPresent = imdbMetaData && (imdbMetaData !== 'undefined') && (imdbMetaData !== "N/A");
var imdbVoteCount = null;
var imdbRating = null;
var imdbId = null;
if (imdbRatingPresent) {
var imdbMetaDataArr = imdbMetaData.split(":");
imdbRating = imdbMetaDataArr[0];
imdbVoteCount = imdbMetaDataArr[1];
imdbId = imdbMetaDataArr[2];
}
var imdbHtml = 'IMDb rating : ' + (imdbRatingPresent ? imdbRating : "N/A") + (imdbVoteCount ? ", Vote Count : " + imdbVoteCount : "");
if (imdbId !== null) {
imdbHtml = "<a target='_blank' href='https://www.imdb.com/title/" + imdbId + "'>" + imdbHtml + "</a>";
}
div.innerHTML = imdbHtml;
div.className = 'imdbRating';
div.id = divId;
synopsis.parentNode.insertBefore(div, synopsis);
}
}
function getDivId(name, year) {
name = name.replace(/[^a-z0-9\s]/gi, '');
name = name.replace(/ /g, '');
return "aaa" + name + "_" + year;
}
function makeRequestAndAddRating(name, year) {
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + encodeURI(name)
+ "&y=" + year + "tomatoes=true";
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (xhr.status === 200) {
var apiResponse = JSON.parse(xhr.responseText);
var imdbRating = apiResponse["imdbRating"];
var imdbVoteCount = apiResponse["imdbVotes"];
var imdbId = apiResponse["imdbID"];
var imdbMetaData = imdbRating + ":" + imdbVoteCount + ":" + imdbId;
window.sessionStorage.setItem(name + ":" + year, imdbMetaData);
window.sessionStorage.setItem("metaScore:" + name + ":" + year, metaScore)
window.sessionStorage.setItem("rotten:" + name + ":" + year, rottenRating);
addIMDBRating(imdbMetaData, name, year);
addRottenRating(rottenRating, name, year);
addMetaScore(metaScore, name, year);
}
};
xhr.send();
}
if (window.sessionStorage !== "undefined") {
var target = document.body;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
window.setTimeout(fetchMovieNameYear, 5);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
}
It would be helpful for you to post the request and response for OMDB (you can find them in the "Network" tab in dev tools).
One thing that triggers CORS (cross-origin requests) errors is specifying a content type other than application/x-www-form-urlencoded, multipart/form-data or text/plain. If I recall correctly, the OMDB API will return a JSON response even without specifying the content type of the request, so you should try removing the line:
xhr.setRequestHeader('Content-Type', 'application/json');
More on "Simple Requests" which do not trigger CORS: https://javascript.info/fetch-crossorigin#simple-requests
You also need to get an API key (https://www.omdbapi.com/apikey.aspx) and replace
**{API_KEY}** in your code with the key. You also need to add the t key to your querystring or the title will be appended to your API key.
var url = "https://www.omdbapi.com/?i=tt3896198&apikey=**{API_KEY}**" + "&t="
+ encodeURI(name) + "&y=" + year + "tomatoes=true";
I have a input for searching in my website and I assign onkeyup event for that.
For example my string is : 'hello world' and when the user types 'llo'(or anything else)show the matched characters as highlighted with the other characters in search list below input.(like google search)
I try this but my code works for the first character not the all characters of string
My code :
//html
<input type="text" onKeyUp="search_customer(this)">
<div class="data_list"></div>
//javascript
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(var i = 0 ; i < res.length ; i++){
if(res[i].full_name.substr(0 , input.value.length) == input.value){
var str = '<strong>'+res[i].full_name.substr(0 , input.value.length)+'</strong>' + res[i].full_name.substr(input.value.length);
var p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}
You can use indexOf to get first index in the matched string and then calculate the last index. Also it's better to use the method slice to be able to use a negative index.
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(let i = 0 ; i < res.length ; i++){
let search = input.value;
let match;
let lastIndx = (res[i].full_name.length-1) - res[i].full_name.indexOf(search) - (search.length-1);
if(lastIndx == 0){
match = res[i].full_name.slice(res[i].full_name.indexOf(search), res[i].full_name.length);
}else{
match = res[i].full_name.slice(res[i].full_name.indexOf(search), -lastIndx);
}
let str = res[i].full_name.slice(0, res[i].full_name.indexOf(search) ) + '<strong>' + match + '</strong>'+ res[i].full_name.slice(res[i].full_name.length-lastIndx, res[i].full_name.length);
let p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}
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 need some help with reading cookies. My website is bilingual, and as I do not want to change language based on IP, I need to be able to set a cookie which I'll call '_lang' and see if the contents are 'en' or 'jp'. I can set the cookie and its contents, no problems, but I can't work out the syntax for reading cookie contents; this is the first time I've actually tried it.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
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 GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;
}
return null;
}
var visit=getCookie("_lang");
var rc=readCookie("_lang");
if (visit==true){
if (rc == "jp"){
window.location = "http://jp.mywebsite.com";
}
else if (rc == "en"){
window.location = "http://www.mywebsite.com";
}
}
else if (visit==null){
document.title = "Welcome to MyWebsite!"
document.getElementById('welcomeLB').style.display='block';
document.getElementById('behindLightBox').style.display='block';
}
I would recommend to use plugin. https://github.com/pavelkukov/localdata
in your case:
var lang_cookie = readCookie('user_lang') ;
if( lang_cookie && lang_cookie !== null && lang_cookie !== 'undefined')
{
if(lang_cookie === 'en')
{
document.location = 'http://en.mysite.com';
}
document.location = 'http://jp.mysite.com';
}
document.location = 'http://en.mysite.com';
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()