JS - why is this not working - any bug? - javascript

I have this code, which adds page=value search parameter to url and loads the page. but this is not working, it is not setting the url, do i have any typo there?
$(function(){
$('.page').on('click',function(){
var page = $(this).text();
var url = String(window.location);
var newurl = "";
if(url.indexOf("?") !== -1){
if(url.indexOf('page') !== -1){
newurl = url.replace(/([&?]page=)[^&]*/, "$1" + String(page));
window.location = newurl;
}else{
newurl = url +'&page='+String(page);
window.location = newurl;
}
}else{
newurl = url +'?page='+String(page);
window.location = newurl;
}
});
});
html
1
2
3
4

the browser is following the href of your links.
Use preventDefault to fix your script.
$(function(){
$('.page').on('click',function(e){
e.preventDefault();
var page = $(this).text();
var url = String(window.location);
var newurl = "";
if(url.indexOf("?") !== -1){
if(url.indexOf('page') !== -1){
newurl = url.replace(/([&?]page=)[^&]*/, "$1" + String(page));
window.location = newurl;
}else{
newurl = url +'&page='+String(page);
window.location = newurl;
}
}else{
newurl = url +'?page='+String(page);
window.location = newurl;
}
});
});

Related

URL Object add or remove params

I am trying to add value of each checkbox to URL searchParams, first time when I check a checkbox it works good, but when I reload page, it not work anymore, what I have done wrong? I mean it works when it is state but after page load, not working, how can I fix this?
function setURL(query){
//var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var url = window.location.href;
let newURL = new URL(url);
newURL.searchParams.append('brands', query)
window.history.replaceState(null, null, newURL);
}
function checkURL(){
var url = window.location.href;
let newURL = new URL(url);
window.history.replaceState(null, null, newURL);
if(newURL.searchParams.has('brands')){
let currentBrands = newURL.searchParams.get('brands');
let brandsArray = currentBrands.split(',');
brandsArray.map(function(v,i){
jQuery('input[name="pa_brand"][value="'+v+'"]').click();
});
}
}
checkURL();
let array = [];
jQuery('input[name="pa_brand"]').change(function(){
let value = this.value;
let id = array.indexOf(value);
if(jQuery(this).is(':checked')){
array.push(value)
} else {
array.splice(id, 1);
}
setURL(array.toString())
console.log(array)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="pa_brand" value="116"/>
<input type="checkbox" name="pa_brand" value="117"/>
<input type="checkbox" name="pa_brand" value="118"/>
First of all replace newURL.searchParams.append('brands', query) with newURL.searchParams.set('brands', query). It will solve your problem also in the checkURL put initial value to array variable. I edited your code after these two changes and everythin seems ok.
let array = [];
function setURL(query){
//var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
var url = window.location.href;
let newURL = new URL(url);
newURL.searchParams.set('brands', query)
window.history.replaceState(null, null, newURL);
}
function checkURL(){
var url = window.location.href;
let newURL = new URL(url);
window.history.replaceState(null, null, newURL);
if(newURL.searchParams.has('brands')){
let currentBrands = newURL.searchParams.get('brands');
let brandsArray = currentBrands.split(',');
array = brandsArray;
brandsArray.map(function(v,i){
jQuery('input[name="pa_brand"][value="'+v+'"]').click();
});
}
}
checkURL();
jQuery('input[name="pa_brand"]').change(function(){
let value = this.value;
let id = array.indexOf(value);
if(jQuery(this).is(':checked')){
array.push(value)
} else {
array.splice(id, 1);
}
setURL(array.toString())
console.log(array)
})

pass argumant in url without clean other argumant use js

i use Paginator django and when i click on pages button. url changes to this : /admin/orders/?page=2
now i want to set status in url arguments like this :
/admin/orders/?status=1.
it works!
but in this case when i change page , status parameter is cleaned!
i want to set both of parameter in url like this :
/admin/orders/?status=1&page=2
how can i solve this problem with js and get a clean url like above?
this my idea but doesn't work :
$(document).ready(function(){
$("#status-filter").click(function(){
var s = $("#status-value").val();
if(window.location.href.indexOf("?") > -1)
window.location.href = window.location.href+"&status="+s;
else
window.location.href = window.location.href+"?status="+s;
})
});
i found it!
i should this code :
function getParameter(name,href){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setUrlParameter(name,value){
var url = window.location;
var href = url.href;
var search = url.search;
var val = getParameter(name,href);
if(val != ''){
var param = name+'='+val;
var new_param = name+'='+value;
var newUrl = href.replace(param,new_param);
window.history.pushState("string", "Title", newUrl);
return false;
}
else if(search == ''){
var param = '?'+name+'='+value;
var newUrl = href+param;
window.history.pushState("string", "Title", newUrl);
return false;
}
else if(search != ''){
var param = '&'+name+'='+value;
var newUrl = href+param;
window.history.pushState("string", "Title", newUrl);
return false;
}
}
console.log(setUrlParameter("status","1"));

Adding a Parameter to Url with javascript

I am trying to add the parameter "referer=" to my url corresponding to the trafic referer of a new session.
I used some of the code from this topic... but it keeps reloading the page in a loop... then the url is like :
https://example.com?refere=facebookreferer=facebookreferer=facebook
Note:
I have been using this solution 1 :
function addOrUpdateUrlParam(name, value)
{
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
{
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
if (refsplit != "example") {
return addOrUpdateUrlParam("referer", refsplit);
}
}
And this solution 2:
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
if (refsplit != "example") {
return location.search += "referer=" + refsplit;
}
}
Edit 1:
Thanks to Prasanth I improved the code to :
function () {
var ref = document.referrer;
var refsplit = ref.split(".")[1];
var currentUrl = location.href;
var url1 = currentUrl += "?referer="+refsplit;
var url2 = currentUrl += "&referer="+refsplit;
if(currentUrl.indexOf("?") < 0) {
return window.location = url1;
} else {
return window.location = url2;
}
}
However, it is returning both conditions :
https://example.com/?referer=facebook&referer=facebook
Edit 2:
So after many attempts, I achieved it by working with the parameters of the url (location.search) instead of the full url (location.href) :
function addRefererParam () {
var ref = document.referrer; //Get Referrer
var refDomain = ref.match(/[^(?:http:\/\/|www\.|https:\/\/)]([^\/]+)/i)[0]; //Extract Referrer Domain name for better readability
var params = location.search; //Get Url parameters
if (refDomain.match(/mydomain|null|undefined/i)) { //check if domain not null or own domain.
return params ;
} else {
return params += "utm_source=" + refDomain; //create new query string with referrer domain
}
}
However, it is no making a persistent query string through browsing... how can I make the new parameters persistent ?
Obtain the url of the current window and after the domain name just concat your url with &referer=value.
var currentUrl = location.href;
var paramsInUrl = currentUrl.split('&');
var flag = true;
for(var i in paramsInUrl)
{
if(!paramsInUrl[i].includes('referer=')
{
continue;
}
else
{
flag = false;
break;
}
}
if(flag)
{
currentUrl += '&referer='+value;
window.location = currentUrl;
}
For what it's worth (because the more generic question of just how to do this generally is what lead me to this post), I've made a 178 byte helper function that takes in an object of the query parameters you want to add to a url for a GET request (in similar format for how you might add headers to a request) and made an npm package for it here: https://www.npmjs.com/package/add-query-params-to-url
Hopefully this is helpful to some.

Javascript- How to pass two variables in the url?

May be this question is answered before but I'm not getting it. I'm using this code.
function refresh() {
var $var=<?php echo "$var"; ?>
var posm = $("#posm").val();
var url = window.location.href;
var index = url.indexOf('?');
if (index > -1) {
url = url.substring(0, index);
}
url += "?posm=" + posm+"?var"+$var;
window.location.href = url;
}
I want to pass both variables posm and $var. posm is passed but $var is not passed. I want help to solve this issue.
use this code
function refresh() {
var $var='<?php echo $var; ?>';
var posm = $("#posm").val();
var url = window.location.href;
var index = url.indexOf('?');
if (index > -1) {
url = url.substring(0, index);
}
url += "?posm=" + posm+"&var="+$var;
window.location.href = url;
}

How to add name value pair to existing query string

i need to add new name ,value pair to existing query string when the user click on some button.
i'm using jquery for client side operations.
any idea..?
thank in advance!
You could do:
$('#yourId').click(function(){
var href = window.location.href;
var indexOfCanc = href.indexOf('#');
if(indexOfCanc === -1){
if(href.indexOf('?') === -1){
href+="?newparamter=my";
}else{
href+="&newparamter=my";
}
}else{
var newHref = href.substring(0, indexOfCanc);
var locationHash = href.substring(indexOfCanc);
if(href.indexOf('?') === -1){
newHref += "?newparamter=my"+locationHash;
}else{
newHref += "&newparamter=my"+locationHash;
}
}
//use the new href for example reload the page with the new parameter:
window.location.href = href;
});
Using regExp:
var href = window.location.href,
toAdd,
pattern1 = /\?/gi,
pattern2 = /#/gi;
if (href.match(pattern1) != null) { toAdd = "&" }
else { toAdd = "?" }
toAdd += "param=val";
if (href.match(pattern2) != null) {
var arr = href.split('#');
href = arr[0] + toAdd + '#' + arr[1];
}
else { href += toAdd; }

Categories

Resources