26

If the &view-all parameter does NOT exist in the URL I need to add it to the end of the URL along with a value. If it DOES exist then I need to be able to just change the value without creating a new URL because it might, or might not, have other parameters before it.

I found this function but I can't get it to work: https://stackoverflow.com/a/10997390/837705

Here is the code I have using the function above (which I can't get to work): http://jsfiddle.net/Draven/tTPYL/4/

I know how to append the parameter and value already:

<div onclick="javascript: window.location.assign(window.location.href+='&view-all=Yes');">Blah Blah</div>

More Info:

If the URL is http://www.domain.com/index.php?action=my_action then the default "&view-all" value would be "Yes" so the URL they would be directed to when they click the button is http://www.domain.com/index.php?action=my_action&view-all=Yes.

If the URL is http://www.domain.com/index.php?action=my_action&view-all=Yes then when they click the button it would change to http://www.domain.com/index.php?action=my_action&view-all=No​​​

EDIT: Please give me examples. I don't know alot of JS, and I just can't think of a way to do it in PHP.

Community
  • 1
  • 1
Draven
  • 1,467
  • 2
  • 19
  • 47

13 Answers13

67
function setGetParameter(paramName, paramValue)
{
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(paramName + "=") >= 0)
    {
        var prefix = url.substring(0, url.indexOf(paramName + "=")); 
        var suffix = url.substring(url.indexOf(paramName + "="));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    }
    else
    {
    if (url.indexOf("?") < 0)
        url += "?" + paramName + "=" + paramValue;
    else
        url += "&" + paramName + "=" + paramValue;
    }
    window.location.href = url + hash;
}

Call the function above in your onclick event.

Sylvain Gantois
  • 779
  • 1
  • 12
  • 28
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • If paramName=paramValue is not in the end of the url string, then the rest of the url string is removed. Example ?view=test&page=2&sort=asc will get switched to ?view=test&page=3 and the sort parameter gets lost. Otherwise the function is very good. Thank you. – ZurabWeb Jan 14 '14 at 15:47
  • 6
    @Piero it's because there is an error in the code : the following line must be rewrite var suffix = url.substring(url.indexOf(paramName)).substring(url.indexOf("=") + 1); by two lines : var suffix = url.substring(url.indexOf(paramName)); suffix = suffix.substring(suffix.indexOf("=") + 1); – Nico Mar 25 '14 at 21:34
  • @LajosArpad I have edited your post, and done the correction as I described in my previous comment. – Nico Mar 25 '14 at 21:41
  • 4
    I fixed a small bug, where the function handles _#_ in the URL incorrectly and sets the parameter at the end of URL where it should be set right before the _#_. I have put the new function in this pastebin: http://pastebin.com/3R96LKZu – Wertisdk Jun 24 '14 at 08:10
  • @Wertisdk Thanks! Your anchor variable is global though, it should be initiated with a var. – user2602152 Sep 24 '14 at 10:29
  • @user2602152 I have amended the pastebin so anchor is declared correctly – Wertisdk Sep 26 '14 at 10:08
  • FYI it fails when your param is named p : If i want to set p to 'lol' i got http=lol – FLX Feb 23 '15 at 15:44
  • @LajosArpad What If I don't want to reload page? –  Apr 21 '16 at 05:50
  • @RohitKhatri, depends on what you want to do instead. If you want to know what would be the URL, then you can return url + hash instead of assigning it to window.location.href and then use the function. As a matter of fact, one could implement a library based on this idea. The answer was meant to cope with the need to set a get parameter and redirect to the URL, but you can deviate that if you need something else. – Lajos Arpad Apr 21 '16 at 14:35
  • Don't forgot encode param in the function: `var paramName = encodeURI(paramName);` – Nabi K.A.Z. Jun 28 '16 at 05:26
  • @NabiK.A.Z., good point. Let's leave out that from this function, as the paramName and paramValue might already by URI-encoded. Nonetheless, your point is valid and one might decide to do that externally. Maybe the best solution is to create a wrapper, a function which takes those parameters, URI-encodes them and calls setGetParameter – Lajos Arpad Jun 28 '16 at 15:54
  • It refreshes the entire page, I dont want to refresh page, – Umair Ayub Oct 26 '16 at 08:39
  • Then return the result instead of assigning it to window.location.href – Lajos Arpad Oct 26 '16 at 19:08
  • 1
    I found a bug in this code, if the parameter is included in another part of the URL it breaks. For instance my parameter is s and url is http://localhost/index.php?a=0&s=3 , the code above breaks when trying to replace the value of s. To fix it var prefix = url.substring(0, url.indexOf(paramName + "=")); var suffix = url.substring(url.indexOf(paramName + "=")); – Sylvain Gantois Jun 08 '19 at 02:29
8

Why parse the query string yourself when you can let the browser do it for you?

function changeQS(key, value) {
    let urlParams = new URLSearchParams(location.search.substr(1));
    urlParams.set(key, value);
    location.search = urlParams.toString();
}
Jamie
  • 537
  • 7
  • 12
5

All the preivous solution doesn't take in account posibility of the substring in parameter. For example http://xyz?ca=1&a=2 wouldn't select parameter a but ca. Here is function which goes through parameters and checks them.

function setGetParameter(paramName, paramValue)
{
  var url = window.location.href;
  var hash = location.hash;
  url = url.replace(hash, '');
  if (url.indexOf("?") >= 0)
  {
    var params = url.substring(url.indexOf("?") + 1).split("&");
    var paramFound = false;
    params.forEach(function(param, index) {
      var p = param.split("=");
      if (p[0] == paramName) {
        params[index] = paramName + "=" + paramValue;
        paramFound = true;
      } 
    });
    if (!paramFound) params.push(paramName + "=" + paramValue);
    url = url.substring(0, url.indexOf("?")+1) + params.join("&");
  }
  else
    url += "?" + paramName + "=" + paramValue;
  window.location.href = url + hash;
}
Pcs
  • 53
  • 1
  • 3
4

I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:

window.location.search = '?filter=' + my_filter_value

The location.search property allows you to get or set the query portion of a URL.

Andrew
  • 227,796
  • 193
  • 515
  • 708
1

To do it in PHP: You have a couple of parameters to view your page, lets say action and view-all. You will (probably) access these already with $action = $_GET['action'] or whatever, maybe setting a default value.

Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'.

And in the end you just build the url with these values again like

$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;

And thats it.

So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).

Marc
  • 6,749
  • 9
  • 47
  • 78
  • I don't see how that would work if there are more parameters after the `action`. It is possible the URL is `http://www.domain.com/index.php?action=my_action&folder=1&view-all=Yes` – Draven Oct 25 '12 at 07:55
  • Sure, you need all of them, but you have them in PHP anyway to display your page? – Marc Oct 25 '12 at 07:56
1

Some simple ideas to get you going:

In PHP you can do it like this:

if (!array_key_exists(explode('=', explode('&', $_GET))) {
  /* add the view-all bit here */
}

In javascript:

if(!location.search.match(/view\-all=/)) {
  location.href = location.href + '&view-all=Yes';
}
LeonardChallis
  • 7,759
  • 6
  • 45
  • 76
1

though i take the url from an input, it's easy adjustable to the real url.

var value = 0;

$('#check').click(function()
{
    var originalURL = $('#test').val();
    var exists = originalURL.indexOf('&view-all');

    if(exists === -1)
    {
        $('#test').val(originalURL + '&view-all=value' + value++);
    }
    else
    {
        $('#test').val(originalURL.substr(0, exists + 15) + value++);
    }
});

http://jsfiddle.net/8YPh9/31/

interested
  • 324
  • 1
  • 9
1

Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.

This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.

function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1); 
var newQueryString = "";
if (clear)
{
    newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
    var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
    var keyValues = queryString.split('&'); 
    for(var i in keyValues) { 
        var key = keyValues[i].split('=');
        if (key.length > 1) {
            if(newQueryString.length > 0) {newQueryString += "&";}
            if(decode(key[0]) == paramName)
            {
                newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
            }
            else
            {
                newQueryString += key[0] + "=" + key[1];
            }
        }
    } 
}
else
{
    if (url.indexOf("?") < 0)
        newQueryString = "?" + paramName + "=" + paramValue;
    else
        newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}
jimmy0x52
  • 321
  • 4
  • 5
1

i would suggest a little change to @Lajos's answer... in my particular situation i could potentially have a hash as part of the url, which will cause problems for parsing the parameter that we're inserting with this method after the redirect.

function setGetParameter(paramName, paramValue) {
    var url = window.location.href.replace(window.location.hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName));
        var suffix = url.substring(url.indexOf(paramName));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix;
    }else {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + paramValue;
        else
            url += "&" + paramName + "=" + paramValue;
    }
    url += window.location.hash;
    window.location.href = url;
}
MrTristan
  • 739
  • 5
  • 17
0

This is my sample code for rebuild url query string with JS

//function get current parameters
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
        return null;
    }
    else{
        return results[1] || 0;
    }
};

//build a new parameters
var param1 = $.urlParam('param1');
var param2 = $.urlParam('param2');

//check and create an array to save parameters
var params = {};
    if (param1 != null) {
        params['param1'] = param1;
    }
    if (order != null) {
        params['param2'] = param2;
    }

//build a new url with new parameters using jQuery param
window.location.href =  window.location.origin + window.location.pathname + '?' + $.param(params);

I used JQUERY param: http://api.jquery.com/jquery.param/ to create a new url with new parameters.

Tuan Ngo
  • 59
  • 3
0

I need help to adjust my script below or to find a script that could be used on my wordpress site to grab the url suffix parameters from a forward url, then to be added at the button click url for tracking the proper forward ads id.

REASON: parameters are used for advertisement tracking to find out from which ad the user has been forward, even if the user hops from optin page to the sales page by using button click.

Here the goal to reach: 1. An FB ad points to an optin page with tracking code: https://ownsite.com/optin-page/?tid=fbad1 2. At the optin-page there is a button with a setup URL to forward to the sales page, but if clicked then only the URL is forward, but the parameter "?tid=fbad1" is missing. 3. The auto-forward script below (which is working properly) can be used to change for button click forward, but has a limitation as it grab only "tid" parameters instead also utm parameters.

Therefore a script code shall be implemented to establish click buttons (also to style them or use images instead) and while clicking the button to forward to a different sales page with grabbing the suffix parameter form the current optin-page to forward then to sales-page https://ownsite.com/sales-page/?tid=fbad1 also including UTM parameters

Currently, I could have solved this by using an auto-redirect script, but A.) I do not want to use an autoredirect at this page. Better is an event click button used to let the user himself click to forward with the URL parameter included. B.) The tracking ID parameter in this script is limited to "?tid=..." instead I do also want to track the UTM code on button click also i.e. Grab from current page the paramater of URL https://www.optin-page.com/?tid=facebookad1?utm_campaign=blogpost then on button click grab parameters and add to button set URL https://www.sales-page.com/?tid=facebookad1?utm_campaign=blogpost

Please now find here the Code below in use for auto-redirect and grabbing the URL parameters. This code shall be changed now to be able to create a button with a click-event to be redirect then to the forward URL with parameter grabbing of current URL if the button is clicked (as stated above).

    <p><!-- Modify this according to your requirement - core script from https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102 and suffix grabbing </p>
    <h3 style="text-align: center;"><span style="color: #ffffff; background-color: #039e00;">►Auto-redirecting after <span id="countdown">35</span> seconds◄</span></h3>
    <p><!-- JavaScript part --><br /><script type="text/javascript">

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}


    // Total seconds to wait
    var seconds = 45;

    function countdown() {
        seconds = seconds - 1;
        if (seconds < 0) {
            // Chnage your redirection link here
var tid = findGetParameter('tid');
window.location = "https://www.2share.info/ql-cb2/" + '?tid='+tid;
        } else {
            // Update remaining seconds
            document.getElementById("countdown").innerHTML = seconds;
            // Count down using javascript
            window.setTimeout("countdown()", 1000);
        }
    }

    // Run countdown function
    countdown();

</script></p>
user51626
  • 1
  • 2
0
var updateQueryStringParameter = function (key, value) {

    var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
        urlQueryString = document.location.search,
        newParam = key + '=' + value,
        params = '?' + newParam;

    // If the "search" string exists, then build params from it
    if (urlQueryString) {
        var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
        var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');

        if( typeof value == 'undefined' || value == null || value == '' ) { 
            params = urlQueryString.replace(removeRegex, "$1");
            params = params.replace( /[&;]$/, "" );

        } else if (urlQueryString.match(updateRegex) !== null) { 
            params = urlQueryString.replace(updateRegex, "$1" + newParam);

        } else {
            params = urlQueryString + '&' + newParam;
        }
    }

    // no parameter was set so we don't need the question mark
    params = params == '?' ? '' : params;

    window.history.replaceState({}, "", baseUrl + params);
};
Alper Ebicoglu
  • 8,884
  • 1
  • 49
  • 55
-1

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);
devnull69
  • 16,402
  • 8
  • 50
  • 61
Tomas Ramirez Sarduy
  • 17,294
  • 8
  • 69
  • 85