replace url parameter and text using jquery? - javascript

When I click search button the url parameter is taking care of. I need to change that url parameter name and value using jquery.
per example: search button clicked
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&cs=This%20Site
Replace with:
http://testsite/_layouts/OSSSearchResults.aspx?k=deana&s=All%20Sites
I can not modify search button functionality, because it is out of the box functionality.
I can do changing url parameter and value. How can we do that?

Changing the parameter of a URL should be fairly straightfoward:
var param = window.location.href;
var param_q = param.split('?');
var param_ampersand = param_q[1].split('&');
var param_eq_1 = param_ampersand[0].split('=');
var param_eq_2 = param_ampersand[1].split('=');
var new_param_name_1 = 'test';
var new_param_value_1 = 'example';
var new_param_name_2 = 'test2';
var new_param_value_2 = 'example2';
// avoid infinite loop
if ((param_eq_1[0] != new_param_name_1 || param_eq_1[1] != new_param_value_1) || (param_eq_2[0] != new_param_name_2 || param_eq_2[1] != new_param_value_2)) window.location = param_q[0] + '?' + new_param_name_1 + '=' + new_param_value_1 + '&' + new_param_name_2 + '=' + new_param_value_2;
This worked for me in Chrome/FF. This just redirects the parameter - not sure if this is what you're looking for.
EDIT:
Added a logic to handle two parameters.

Related

replace segment of a URL with regex

I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.
Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know
URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]
I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/

Javascript URL Query String Logic

I have an events listing page which can be filtered by type and also by date using query string variables.
I am trying to achieve the following logic using javascript/jQuery.
I have a calendar which fires a function when updated. When fired I need to implement the following logic:
If the current URL contains ?filter= then add &dateStart= to the end of the URL.
If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
If the current URL contains ONLY ?dateStart= then replace it with the new one.
I have tried various methods to achieve this but I keep hitting the problem of appending information to the end of the URL rather than replacing parts of it.
Any help would be appreciated.
Thanks.
You can try something like this:
NOTE: not tested.
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
You can achieve this more easy with native Web API or vanilla javascript than with jQuery. As far as jQuery don't provide any specific function to work with query strings.
The new URLSearchParams object provide a few methods to work more easily with URL query strings. In your case for example you'll need to do something like this:
function updateQueryString(queryString, dateStart) {
var queryString = new URLSearchParams(queryString);
queryString.has('dateStart')
? queryString.set('dateStart', dateStart)
: queryString.append('dateStart', dateStart);
return queryString.toString();
}
for this solution you'll need a polyfill
Sadly this is not yet implemented by the majority of web browsers and you'll need to "polyfill" the URLSearchParams object for this solution to work properly. You'll have to add this line to the <head> section in your html:
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>
You can find more information about the URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C
solution without polyfill
​
If you don't like to use edge features you still can do it without any extra polyfill. It would look like this:
function updateQueryString(queryString, dateStart) {
var qsObject = {};
queryString
.substring(1) // ignore '?'
.split('&').forEach(function (param) {
param = param.split('=');
qsObject[param[0]] = param[1];
});
qsObject['dateStart'] = dateStart;
return '&' + Object.keys(qsObject)
.map(function (key) {
return key + '=' + qsObject[key];
})
.join('?');
}
Call whatever version of the updateQueryString function you rather like this:
updateQueryString(windonw.location.search, dateStart)

access javascript variable into the .ashx page

I have a JavaScript, which returns 2 variables. I just want to access those variables in the generic handler(ashx) page but I can't. Can anybody give some suggestion?
var myArray = [txt, value];
var url = "insertComments.ashx?dat=" + myArray.join();
Change your Javascript :
var url = "insertComments.ashx?datTxt=" + txt + "&" + "datValue=" + value;
and in handler access that values with :
string txt = context.Request.Params["datTxt"];
string val = context.Request.Params["datValue"];

Append to URL and refresh page

I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '&param=1'
}else{
url += '?param=1'
}
window.location.href = url;
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '&param=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "&parameter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
location.href = location.href + "&parameter=" + value;
This line of JS code takes the link without params (ie before '?') and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
One small bug fix for #yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets

Javascript eval

I am trying to get the following working. It seemed to work initially, but somehow it stopped working
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + eval("setCommonAttr")).value;
what is wrong with above?
The above code is little different from what I am trying to accomplish. I gave the above example just not to make things complicated here. Below is what I am trying to accomplish:
First I am getting an existing element as follows. The element is a
<tr id="row_1_4_2009_abc" class="rowclick">
<td></td>
</tr>
I am using jquery to get the id on click of a row:
$(".rowclick").click(function() {
var row_id = $(this).attr("id");
var getAttributes = row_id.split("_");
var setCommonAttr = getAttributes[1] + "_" + getAttributes[2] + "_" + getAttributes[3] + "_" + getAttributes[4];
var new_row_id = document.getElementById("new_row_" + setCommonAttr).value;
});
You shouldn't need eval() to do this. The value you want is already a variable in JavaScript. Try:
var setCommonAttr = "1_row1_common";
var val = document.getElementById("abc_" + setCommonAttr).value;
Will everything be in that form? row_xxx_xxx_xxx_xxx
if so, why not var new_row_id = document.getElementById("new_" + row_id).value;
You don't need to call eval().
You can just concatenate the string with the variable:
var setCommonAttr = "1_row1_common"; var val = document.getElementById("abc_" + setCommonAttr).value;

Categories

Resources