Javascript url.location & replaced with? - javascript

I am having a language selection radio button in my html page and on selection of a language I make the call to the same url appending '?lang='. This I am doing via js and when the url is submitted the & is replaced with ?. Below is my js code.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
$(document).ready(function () {
$('input:radio[name=lang]').change(function() {
var url = window.location.href;
var selectedLang = $(this).attr('id');
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + selectedLang);
window.location = url;
} else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + selectedLang);
window.location = url;
}
} else {
if (url.indexOf('?') >= 0) {
window.location = url + '&lang=' + selectedLang;
} else {
window.location = url + '?lang=' + selectedLang;
}
}
});
});
Now when I make the language selection the url in the browser is http://localhost:8080/test/report.htm?count=40&name=jerry?lang=en. I debugged the code and saw url to be http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en but this is getting changed on submission.

Your code seems to be fine. You should consider to use functions, they make debugging a lot easier.
function removeBookmarkFromUrl(url) {
var arr = url.split("#");
return arr[0];
}
function getLangUrl(url, lang){
url = removeBookmarkFromUrl(url);
if (url.indexOf('?lang') >= 0 || url.indexOf('&lang') >= 0) {
var pos = (url.indexOf('?lang') >=0 ) ? url.indexOf('?lang') : url.indexOf('&lang');
var currentLang = url.slice(pos + 6, pos + 8);
if (url.charAt(pos) == '?') {
url = url.replace('?lang=' + currentLang, '?lang=' + lang);
return url;
}
else if (url.charAt(pos) == '&') {
url = url.replace('&lang=' + currentLang, '&lang=' + lang);
return url;
}
} else {
if (url.indexOf('?') >= 0) {
return url + '&lang=' + lang;
} else {
return url + '?lang=' + lang;
}
}
}
var url;
url = "http://localhost:8080/test/report.htm";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry";
console.log(url, " \n-> ", getLangUrl(url, 'de'));
url = "http://localhost:8080/test/report.htm?count=40&name=jerry&lang=en";
console.log(url, " \n-> ", getLangUrl(url, 'de'));

Related

How to refresh image by setTimeout, when url is getting by ajax?

I am writing a REST client to remote api. And I am using xmlHTTPRequest to get information about images.I need to refresh my images in every 30 seconds. My implementation of setTimeout function doesn't work. Anyone can help me? Thank you in advance.
Here is my code: Image.js
function Camera(id, name, ip, port) {
var button = document.createElement("button");
button.classList.add("camera");
button.innerHTML += "<h3>" + name + "</h3><br>";
var ismin = true;
this.id = id;
this.name = name;
this.ip = ip;
this.port = port;
this.getURL = function getURL(min) {
var url = 'http://' + ip + ":8080/api";
return min ? url + '/miniature/' + id + '?t=' + new Date().getTime() : url + '/image/' + id + '?t=' + new Date().getTime();
};
this.appendImg = function appendImg(url) {
button.innerHTML = "<h3>" + name + '</h3><br><img src="' + url + '"/>';
setTimeout(appendImg(url),30000);
};
this.showElement = function showElement(url) {
this.appendImg(url);
var that = this;
document.querySelector('#camera-section').appendChild(button);
button.addEventListener('click', function () {
ismin = !ismin;
that.appendImg(that.getURL(ismin), false);
});
};}
And a part of main.js:
function showImage(response) {
response = JSON.parse(sessionStorage.getItem('camera'));
console.log(response);
for (var i = 0; i < response.length; i++) {
var a = response[i];
var camera = new Camera(a.cameraId, a.name, ip, port, true);
var curl = camera.getURL(true);
camera.showElement(curl);
}
}
xml.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
sessionStorage.setItem('camera',JSON.stringify(response));
//console.log(sessionStorage.getItem('camera'));
showImage(sessionStorage.getItem('camera'));
}
};
xml.open('GET', mainUrl);
xml.send(null);
Regarding the comment of Pranay Kumar, first part of your code could be like this::
function Camera(id, name, ip, port) {
var button = document.createElement("button");
button.classList.add("camera");
button.innerHTML += "<h3>" + name + "</h3><br>";
var ismin = true;
this.id = id;
this.name = name;
this.ip = ip;
this.port = port;
this.getURL = function getURL(min) {
var url = 'http://' + ip + ":8080/api";
return min ? url + '/miniature/' + id + '?t=' + new Date().getTime() : url + '/image/' + id + '?t=' + new Date().getTime();
};
this._appendImg = function(url) {
return function() {
button.innerHTML = "<h3>" + name + '</h3><br><img src="' + url + '"/>';
}
};
this._timerHandle = 0;
this.appendImg = function(url) {
if (this._timerHandle) {
clearInterval(this._timerHandle);
}
this._timerHandle = setInterval(this._appendImg(url),30000);
}
this.showElement = function showElement(url) {
this.appendImg(url);
var that = this;
document.querySelector('#camera-section').appendChild(button);
button.addEventListener('click', function () {
ismin = !ismin;
that.appendImg(that.getURL(ismin), false);
});
}
}
You want refresh image every 30 seconds.
So use setInterval instead of setTimeout

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

Javascript add into history

I have an ajax based website & i have successfully added support for the back button, which works fine. My issue is that when i go back i can not go forward.
How can i add an a future item in history? Or enable the forward button?
Is there an event to manipulate the forward button?
history buttons
HASHBANG LIBRARY
function hashbang(pages){
this.currentPage = [];
this.currentPageIndex = 0;
this.displayer = true;
var that = this;
this.setup = function(){
N$(window).event('popstate', function(node, event){
console.log('pop');
document.body.style.display = "none";
that.displayer = false;
that.removeResources();
that.currentPageIndex++;
//var hash = (event.state)? event.state.page : window.location.hash.slice(1).replace('!','');
console.log(that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]);
if(pages[that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['src']]){
that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params']['hash'] = '#!' + that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params']['hash'];
that.changePage(that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['src'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['js'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['into'], that.currentPage[that.currentPage.length - 1 - that.currentPageIndex]['params'], true);
}
});
}
this.state = function(page_, update){
N$.ajax('../php/ajax/AJAX_BASE.php', 'post', {}, function(AJAX_BASE){//get base
if(window.history.pushState && window.history.replaceState){//compatibility check
if(!update){
if(window.history.state != null){
if(window.history.state.page != page_){// if page is not page_
window.history.pushState({page: page_}, '', AJAX_BASE+page_);//push page into history
}else{
try{
window.history.replaceState({page:page_}, '', AJAX_BASE+page_);
}catch(error){
}
}
}else{
window.history.pushState({page: page_}, '', AJAX_BASE+page_);
}
}else{
window.location.hash = '!'+page_;
}
}
}, true);
}
this.loadPage = function(src, func_array, into, params, prevent_push){
console.log('loadPage:::: ' + src);
if(typeof params != typeof {})
params = {};
if(params['hash'] == undefined){
params['hash'] = window.location.hash;
}else{
params['hash'] = params['hash'];
}
this.state(src + params['hash'], false);
params['hash'] = params['hash'].replace(/#!/g, "-").slice(1);
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
N$.loadCSS(src + '_' + mobile + '.css', function(){
N$.ajax(src + '_' + mobile + '.php', 'POST',params, function(page_content){
N$(into).innerHTML(page_content);
if(func_array['initialize'])
func_array['initialize'](params);
console.log('attempted::' + src + '_' + mobile + '.js');
N$.loadJS(src + '_' + mobile + '.js', function(){
console.log('loaded::' + src + '_' + mobile + '.js');
if(func_array['execute'])
func_array['execute'](params);
});
if(func_array['terminate'])
func_array['terminate'](params);
if(!that.displayer)
document.body.style.display = "block";
}, false);
});
if(!prevent_push || prevent_push == undefined || prevent_push == null){
console.log('page pushed');
var pusher = {
'src': src,
'params': params,
'js': func_array,
'into': into
};
console.log(pusher);
that.currentPage.push(
pusher
);
}
}
this.loadPartial = function(src, func_array, into, params){
src = '/i/partials/' + src;
if(typeof params != typeof {})
params = {};
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
N$.loadCSS(src + '_' + mobile + '.css', function(){
N$.ajax(src + '_' + mobile + '.php', 'POST',params, function(page_content){
N$(into).innerHTML(page_content);
if(func_array['initialize'])
func_array['initialize']();
N$.loadJS(src + '_' + mobile + '.js', function(){
if(func_array['execute'])
func_array['execute']();
});
if(func_array['terminate'])
func_array['terminate']();
}, false);
});
}
this.changePage = function(src, func_array, into, params, prevent_push){
console.log('changePage:::: ' + src);
document.body.style.display = "none";
this.displayer = false;
this.removeResources();
this.loadPage(src, func_array, into, params, prevent_push);
}
this.removeResources = function(){
var mobile = ( (browser)?( (browser.loaded_mobile)? browser.loaded_mobile : false ): false);
if(this.currentPage[this.currentPage.length - 1]){
N$.removeResource(this.currentPage[this.currentPage.length - 1]['src']+ '_' + mobile +'.css', N$.globals.loaded_css);
N$.removeResource(this.currentPage[this.currentPage.length - 1]['src']+ '_' + mobile +'.js', N$.globals.loaded_script);
}
}
}
This library works in adjacent to other libraries. My interest is on the popstate event

Pagination with Javascript Went Wrong

I've coding pagination with JS
out like this
<a id="prev">Previous Page</a>
<a id="next">Next Pages</a>
and JS Code like this
$('#next').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = parseInt((url.substr(urllen-1)).substr(0,1));
var nurl = url.substr(0,(urllen-1))+(cur+1);
if(cur=="NaN") { window.location = (url); }
else { window.location = (nurl); }
});
$('#prev').click(function(){
var url = window.location.href;
var urllen = url.length;
var cur = (url.substr(urllen-1)).substr(0,1);
if(cur==1||cur=="NaN") { window.location = (url); }
else { var nurl = url.substr(0,(urllen-1))+(cur-1); window.location = (nurl); }
});
and my url like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=1
let's me explain the reason that i'm using a JavaScript method is i don't want to change my URL that containing page variable that i use in my whole page
so what i'm doing is get all the URL and change bike_id value to next/prev
and the problem is when it count to 19 or URL like
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
then i goes next again the URL will become
http://localtest/rftpages/record.html?s=1&l=1&bike_id=110
any idea/suggestion to fix this ?
Thanks
What you should do is grab the page from the query string and the either increment or decrements it based on what is clicked.
all you need is this function to get the parameters:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
So if I assume your example:
http://localtest/rftpages/record.html?s=1&l=1&bike_id=19
Then you can change your function to be:
$('#next').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage + 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});
$('#prev').on("click", function() {
var currentPageParameter = getParameterByName("bike_id");
var s = getParameterByName("s");
var l = getParameterByName("l");
var myPage = parseInt(currentPageParameter);
if (! isNaN(myPage )) {
myPage = myPage - 1;
window.location = location.protocol + '//' + location.host + location.pathname + "?s=" + s + "&l=" + l + "&bike_id=" + myPage;
}
});

prev / next nav codes to be more efficient and flexible

I have working codes that sets the Prev and Next URL based on the available pages numbers and the URL you are currently on.
My codes are way too long and not flexible at all. How can I make it more flexible and production ready?
http://jsfiddle.net/sunflowersh/ppDL7/5/
var currentindex = '4'; //updated based on the current index data
var indexNum = parseInt(currentindex);
var currentURL = document.location.href.substring(document.location.href.lastIndexOf("/")+1, document.location.href.length);
var baseURL ="/en_US/";
var leftURL = "";
var rightURL = "";
switch(indexNum)
{
case 2:
// if there are only index, index1, and index2
if((currentURL.indexOf("index.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 3:
// if on index3.html or index.html
// make the right arrow URL go back to index1.html
if((currentURL.indexOf("index3.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-2) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 4:
if((currentURL.indexOf("index4.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-3) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
case 5:
if((currentURL.indexOf("index5.html")>-1)||(currentURL.indexOf("index.")>-1)){
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum-3) + ".html";
} else {
leftURL= baseURL + "index" + parseInt(indexNum-1) + ".html";
rightURL= baseURL + "index" + parseInt(indexNum+1) + ".html";
}
break;
default:
// if no current index, disable the link
leftURL= baseURL + "#";
rightURL= baseURL + "#";
}
var leftArrow =$(".leftArrow").find("a").attr("href",leftURL);
var rightArrow =$(".rightArrow").find("a").attr("href",rightURL);
Have a see at this http://jsfiddle.net/steelywing/ppDL7/6/
Create a index.js
var baseURL = "/en_US/index";
var maxIndex = 4;
function updateNav(index) {
if (index-1 > 0) {
$('.leftArrow a').attr('href', baseURL + (index-1) + '.html');
} else {
$('.leftArrow a').hide();
}
if (index+1 <= maxIndex) {
$('.rightArrow a').attr('href', baseURL + (index+1) + '.html');
} else {
$('.rightArrow a').hide();
}
}
and, in every index.html, call updateNav() onLoad
<script>updateNav(2); // 2 current index </script>
If you need to parse the URL, try using RegExp /\/index(\d+)\.html$/ (http://jsfiddle.net/steelywing/uex5m/)
MVC design would suggest rendering Next & Prev URLS on the server, which knows how many pages there are in total;
Or at least rendering a pre-prepared 'base URL' and 'pageCount' into JS variables, so producing a valid URL is trivial in Javascript.
An example in JSP:
<script type='text/javascript'>
var baseUrl = ${baseUrl};
var numPages = ${numPages};
var currPage = ${currPage};
function changePage (delta) {
var newPage = ((currPage + delta) % numPages); // 0-based.
var newUrl = baseUrl + newPage + ".html";
// var newUrl = baseUrl + newPage;
window.location = newUrl;
}
$(document).load( function(){
$(".leftArrow a").click( function(){
changePage(-1)});
$(".rightArrow a").click( function(){
changePage(+1)});
});
If your page-numbers are 1-based, the % 'modulus' expression either has to be more complex (subtract 1 beforehand, add 1 after) or you can do an if statement.
function changePage (delta) { // 1-based PageNumber version.
var newPage = currPage + delta;
if (newPage <= 0) newPage = numPages;
if (newPage > numPages) newPage = 1;
// ... as before.
Or via modulo:
var newPage = ((currPage-1 + delta) % numPages) + 1;
Pick which you find clearest & most maintainable, if you were coming back to the code in 2 years time!
[Edited] If no server-side smarts at all, just put constants into the JS. You can also separate the constants/or calculation of base-URL, from the active part of the script.. thus making it reusable across several pages.
If i understand your use case correctly, this should do what you want:
$(function () {
var total = 3; // index.html, index1.html, index2.html
var currentIndex = 0; // index.html
var base = '/en_US/';
var pagename = 'image'; // for pattern: index<number>.html
function getNavUrl(delta) {
var newIndex = (currentIndex + delta < 0) ? total - 1 : (currentIndex + delta) % total;
newIndex = (newIndex === 0) ? '' : newIndex;
return base + pagename + newIndex + '.html';
}
$(".leftArrow a").click(function () {
window.location = getNavUrl(-1); // /en_US/index2.html
});
$(".rightArrow a").click(function () {
window.location = getNavUrl(+1); // /en_US/index1.html
});
});
version with more detailed comments: http://jsfiddle.net/ppDL7/8/
Update:
After figuring out the exact recuirements, here is the final version. Also added index parsing from document.location.href:
$(function () {
var total = 4;
var base = '/en_US/';
var pagename = 'index'; // for pattern: index<number>.html
var currentIndex; // index.html === index[last].html
var href = document.location.href;
function extractIndex(url){
var regExp = new RegExp(pagename+'(\\d+)\.html$');
var match = url.match(regExp);
var index = match? match[1] : null; // null if url does not match
// interpret index.html as index[last].html:
return (!index)? total : +index;
}
function getNavUrl(delta) {
var newIndex;
if(currentIndex +delta <= total){
newIndex = (currentIndex + delta <= 0) ? total : (currentIndex + delta) % (total+1);
} else {
newIndex = (delta < 0)? total - delta : delta;
}
return base + pagename + newIndex + '.html';
}
function setCurrent(index){
$('.current').html('<b> ' + index + '</b>');
}
currentIndex = extractIndex(href);
$(".leftArrow a").click(function () {
window.location = getNavUrl(-1);
});
$(".rightArrow a").click(function () {
window.location = getNavUrl(+1);
});
});
http://jsfiddle.net/ppDL7/12/

Categories

Resources