When a user navigates to my site with a qualified URL (e.g. mysite.com/abc.html) I want to call a javascript function first before showing any pages. I need that because my site is driven by ajax.
I have a function that’s called when the page is first loaded:
<body onload="FirstJSFunction(150);”>
That function will intercept the URL and do what I want, but only if the qualified URL is mysite.com/index.html. Any other valid URL within the site will bypass the javascript function and load the requested page. That’s not what I want.
Here is how FirstJSFunction handles it:
<script>
function FirstJSFunction(type) {
var gurl = GetURL();
length = gurl.length;
console.log("SFR URL " + length);
var pos = gurl.lastIndexOf("/");
console.log ("SFR_LastFwdSlash " + pos);
if (length > pos) {
var sub1 = gurl.substr(pos, length);
console.log ("SFR_Sub1 " + sub1);
sub2 = sub1.substr(1, 5);
console.log ("SFR_Sub2 " + sub2);
if (sub2 == "index") {
ShowAjax(3);
return true; }
if (sub2 != "index") {
ShowAjax(3);
return true; }
}
</script>
<script>
function GetURL() {
var loc_href = location.href;
console.log ("URL " + loc_href);
var length = loc_href.length;
console.log ("Length " + length);
var pos = loc_href.lastIndexOf("/");
console.log ("LastFwdSlash " + pos);
var pos2 = loc_href.indexOf("/");
console.log ("FwdSlash " + pos2);
if (length > pos) {
var substr = loc_href.substr(pos, length);
console.log ("Substring " + substr);
return substr; }
}
</script>
So my question is: when the user navigates to my site with any URL other than mysite.com or mysite.com/index.html – for example mysite.com/abc.html – why doesn’t the code above work to intercept the URL and call the javascript function, as happens if the URL is index.html.
Just to clarify, I only want to intercept the first incoming URL. I am not looking to intercept any URL the user enters into the address bar after they have arrived at my site.
Thanks for any help on this.
I'm not sure about everything you explained, so making some assumptions here.
But if that JS code is only on index.html, then it will never run for any other page. For that you would need to include it in every page.
Only the server is able to "see" all the pages accessed by your users.
Related
I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.
I am developing a website that works in two languages. I need to change URL to include the selected language.
What I exactly need is:
Pick the current URL
Check if the URL contains any language code
Append the code if not exist or change the code to the selected one if exists
For example, there is an URL for English (default):
http://localhost:11767/Home/resultMain?model=1&&type=1
When a user selects Spanish (es) it should be:
http://localhost:11767/es/Home/resultMain?model=1&&type=1
You can parse the URL with the help of an a element then replace the part you want and re-build the URL :
function addReplaceLangCode(url, langCode) {
var a = document.createElement('a');
a.href = document.getElementById('url').value; // or document.location.href;
var paths = a.pathname.split('/');
paths.shift();
if(paths[0].length == 2) {
paths[0] = langCode;
}else{
paths.unshift(langCode);
}
return a.protocol + '//' +
a.host + '/' + paths.join('/') +
(a.search != '' ? a.search : '') +
(a.hash != '' ? a.hash : '');
}
function onClickReplace() {
document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>
I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.
But generally I recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.
https://www.w3.org/International/questions/qa-accept-lang-locales
Based on #Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://stackoverflow.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};
I have this jzebra applet that I need to do some client side ticket printing.
This is the applets html definition:
<applet id="jzebra" name="jzebra" code="jzebra.PrintApplet.class" archive="../../../../../../web/org.openbravo.howtos/lib/jzebra.jar"
width="10px" height="10px">
The function I call in the form button is this:
function printDocument() {
var applet = document.jzebra;
var frm = document.frmMain;
var url = frm.elements["inpftpOBDir"].value;
var file ="0.txt";
var archivo = url + "/" + file;
if (applet != null) {
var printname = frm.elements["inpPrinterName"].value;
var indice = frm.inpPrinterSelected.selectedIndex;
var printselected = frm.inpPrinterSelected.options[indice].text;
alert(printname);
alert(printselected);
if(printselected == ""){
// printname = "zebra"
//alert('Default : ' + printname);
applet.findPrinter(printname);
monitorFinding();
} else {
//alert('Selected : ' + printselected);
applet.findPrinter(printname);
monitorFinding();
}
alert('File : ' + archivo);
// applet.findPrinter(printname);
applet.appendFile(archivo);
// Send characters/raw commands to printer
applet.print();
alert('The document was sent to the printer.');
}
}
I checked the console and there is a definition of applet, but when it reaches applet.findPrinter(printname), just explodes because applet.findPrinter is not a function.
Has anyone faced this struggle before? I have seen that there is a little gray square in the top left corner of my page. When I hover on it, it displays "undefined".
I finally came up with a very complex solution, having to use jnlp. I will post my code later for references, if anyone else find similar problems.
I need to add a 'Send Message' button which takes the username of the user that message will be sent to, goes to a link and put this username to the 'To' field of the message form.
This is my code
function sendmessage() {
var x;
//geting the username
x = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = x.substring(x.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
//to get the username parameter from URL on new page
var z=window.location.search.substr(1);
//to get rid of some part of the username parameter
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
//to put the username to 'To' field
document.getElementById("search-q").value= a;
}
Now the problem is that the new page is opened with the parameter. And as a seperate case I can get a parameter from a URL then put it in a field. But I cannot do these two together.
Thanks for the answers!
What you are trying to do is impossible.
As I said in my comment you are navigating away from the page when you set the location. The code after that will not run on the next page. That code needs to live on the next page. That code would have to be executed on page load or document ready.
ok. thanks for the answers. I solve the issue and it works. I am posting the code to help anyone struggling on this problem like me.
The code is divided into two pieces.
<script>
function sendmessage() {
var y;
//geting the username
y = document.getElementsByClassName('sol-kkutu')[0].innerHTML;
var x = y.substring(y.indexOf(":") + 1);
//passing the username parameter by URL
window.location.href = "http://ogrencidenilan.net/mesajlar-2?fepaction=newmessage"+"&" + x;
}
</script>
<script>
//code running after page-load
window.onload = function() {
var z=window.location.search.substr(1);
var a = z.substring(z.indexOf("0") + 1);
a = a.substring(0, a.length - 8)
document.getElementById("search-q").value= a;
}
</script>
I initially wrote a small ajax-based settings page for an online support system i developed, using jQuery 1.4.2 and it worked fine. However, after upgrading to 1.6.1, additional executions are being called to the functions that were only ever called once previously.
I have three menu options, each with an onclick event to load a specific page into the #settingsph div. Additional code is then called depending on the page in question. (The apache server automatically assumes .php file ext are to be used if none are defined)
function open_page(name) {
$("#settingsph").load("/includes/support/stg/"+name, function(){
if(name == "managecontacts"){
$("#contactselect").load("/includes/support/stg/contactsel");
}else if(name == "changepw"){
$(change_pw(), "changepw_box");
}else if(name == "editcompany"){
$(company_update(), "#company_update");
}
});
}
Once loaded, a select box is presented to users, to select a contact to edit. Onchange, the following function is called.
function open_contact(id) {
$("#contact_info").load("/includes/support/stg/editcontact?id="+id);
if(id != "NewContact") {
$(contact_update(), "#contact_update");
}else{
$(contact_add(), "#contact_add");
}
}
Let's assume the user has decided to edit their contact information (all 3 update pages use roughly the same function, but with the variables changed to reflect the page it took information from).
function contact_update() {
$('input.text-input').css({backgroundColor:"#ffffe0"});
$('input#ldate').live('focus', function(){
$(this).datepick({dateFormat: 'dd/mm/yy'});
});
$("input.text-input").live('focus', function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$("input.text-input").live('blur', function(){
$(this).css({backgroundColor:"#ffffe0"});
});
$('.error','#contact_info').hide();
$(".buttonupd").live('click', function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var forename = $("input#forename").val();
if (forename == "") {
$("label#forename_error").show();
$("input#forename").focus();
$('input#forename').css({border:"solid #aa0000"});
}else{
$('input#forename').css({border:""});
}
var surname = $("input#surname").val();
if (surname == "") {
$("label#surname_error").show();
$("input#surname").focus();
$('input#surname').css({border:"solid #aa0000"});
}else{
$('input#surname').css({border:""});
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
$('input#phone').css({border:"solid #aa0000"});
}else{
$('input#phone').css({border:""});
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
$('input#email').css({border:"solid #aa0000"});
}else{
$('input#email').css({border:""});
}
if((forename == "") || (surname == "") || (phone == "") || (email == "")){
return false;
}
var contactid = $("input#contactid").val();
var jobtitle = $("input#jobtitle").val();
var site = $("select#site option:selected").val();
var mobile = $("input#mob").val();
var ldate = $("input#ldate").val();
var loginallowed = $("input[name='loginallowed']:checked").val();
var editaddress = $("input[name='editaddress']:checked").val();
var editcontacts = $("input[name='editcontacts']:checked").val();
var editcompany = $("input[name='editcompany']:checked").val();
var lognewissue = $("input[name='lognewissue']:checked").val();
var viewallissues = $("input[name='viewallissues']:checked").val();
var viewchangelog = $("input[name='viewchangelog']:checked").val();
var viewdownloads = $("input[name='viewdownloads']:checked").val();
var newissuenotify = $("input[name='newissuenotify']:checked").val();
var closeissuenotify = $("input[name='closeissuenotify']:checked").val();
var changelognotify = $("input[name='changelognotify']:checked").val();
var viewsitehardware = $("input[name='viewsitehardware']:checked").val();
var viewcompanyhardware = $("input[name='viewcompanyhardware']:checked").val();
var dataString = 'contactid=' + contactid + '&forename=' + forename + '&surname=' + surname + '&jobtitle=' + jobtitle + '&site=' + site + '&email=' + email + '&phone=' + phone + '&mob=' + mobile + '&ldate=' + ldate + '&loginallowed=' + loginallowed + '&editaddress=' + editaddress + '&editcontacts=' + editcontacts + '&editcompany=' + editcompany + '&lognewissue=' + lognewissue + '&viewallissues=' + viewallissues + '&viewsitehardware=' + viewsitehardware + '&viewcompanyhardware=' + viewcompanyhardware + '&viewchangelog=' + viewchangelog + '&viewdownloads=' + viewdownloads + '&newissuenotify=' + newissuenotify + '&closeissuenotify=' + closeissuenotify + '&changelognotify=' + changelognotify;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/includes/support/stg/contactupd",
data: dataString,
success: function() {
$('#contact_update').html("<div id='contact_upd_msg'></div>");
$('#contact_upd_msg').html("<h2>Contact Successfully Updated</h2>")
.append("<p>Thank you.</p>")
.hide()
.fadeIn(1500, function() {
$('#contactselect').html("")
$("#contactselect").load("/includes/support/stg/contactsel");
});
}
});
return false;
});
}
The first time the function is executed, it is called only once and appears to be fine. However, if the above function is called a second time to perhaps update another contact, two requests are sent, updating the information twice and refreshing the select box with a list of contacts in twice. If the above function is called a third time, three requests are sent and so on until the page is completely refreshed. I reverted back to 1.4.2 and these functions are only ever executed once, regardless of how many times they're called without a page refresh.
The .live() method was introduced to me here on SO when i first wrote the system and worked well at the time since the .buttonupd does not exist in the DOM when the settings.php page is loaded, is this my problem?
As was mentioned in the comment, you shouldn't be attaching events within a function which could be called multiple times. Each time you call live within that function you are attaching a new event handler. That's why if that method gets called 3 times, triggering the event will cause the handler to run 3 times.
Here is a stripped down example:
http://jsfiddle.net/N78MX/
Notice that every time you click, the number of words added increases by one. This is because each click calls live and attaches another handler.
You can fix this by simply moving all of your live calls outside of your function. Since you are using live it is fine to call it prior to the elements in question being created. So the stripped down example becomes this:
http://jsfiddle.net/N78MX/1
and it works no matter how many times you click. (obviously if this were a real page I would combine those two live calls, but this is just for illustration).