Karolis
Karolis

Reputation: 2618

jQuery append params to url

I like the way jQuery's $.ajax() method allows to specify request url:

{
  url: 'http://domain.com/?param=1',
  data{
    param2: '2'
  }
}

$.ajax() method will (probably) call $.param() on provided data and optionally append it to provided URL.

My question is: is this type of url manipulation available outside of $.ajax() call?

For example, I want to open a popup window, and I would like to construct URL in the same way that I do with $.ajax().

I have written a function which does this, but I have a feeling I am reinventing the wheel and duplicating already existing function of jQuery:

var prepareUrl = function( url, data )
{
  var params = $.param( data );

  if ( params.length > 0 )
  {
    // url contains a query string
    if ( url.indexOf( '?' ) > -1 )
    {
      // get last char of url
      var lastChar = url.substr( url.length - 1 );

      // Append & to the end of url if required
      if ( lastChar != '&' && lastChar != '?' )
      {
        url += '&';
      }
    }

    else // url doesn't contain a query string
    {
      url += '?';
    }

    url += params;
  }

  return url;
}

thanks!

Upvotes: 13

Views: 28419

Answers (5)

Anupam
Anupam

Reputation: 15620

As mentioned in this SO answer, just use URLSearchParams

let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);

where key=value is new url parameter that you want to add

You could check the browser compatibility here

Upvotes: 1

Karolis
Karolis

Reputation: 2618

Since other replies didn't answer my question, i have made a few tests with the $.ajax() call to see how it merges urls with param data.

My findings so far:

  • if url contains a ?, then $.ajax() will append '&' + $.param(data)
  • if not, then $.ajax() will append '?' + $.param(data)

So if I want to keep my url processing function consistent with the way $.ajax() does it, then it should be something like the following:

  var addParams = function( url, data )
  {
    if ( ! $.isEmptyObject(data) )
    {
      url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
    }

    return url;
  }

I am still wondering if there is a built-in jQuery method to do this.

Upvotes: 7

kasper Taeymans
kasper Taeymans

Reputation: 7026

yes you can use jqueries .param() function to do this.

jsfiddle demo

var params = { param1:"foo", param2:"bar"};
var str = jQuery.param( params );
alert(str);

Upvotes: 3

Shreejibawa
Shreejibawa

Reputation: 1868

You can build query string like this:

getQueryStr = function(obj) {
    var str = [];
    for (var p in obj)
        if (obj.hasOwnProperty(p)) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
    return str.join("&");
}

console.log(serialize({
    param1: "val1",
    param2: "val2"
}));

For recursive :

getQueryStr = function(obj, prefix) {
    var str = [];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            var k = prefix ? prefix + "[" + p + "]" : p,
                v = obj[p];
            str.push(typeof v == "object" ?
                getQueryStr(v, k) :
                encodeURIComponent(k) + "=" + encodeURIComponent(v));
        }
    }
    return str.join("&");
}

console.log(serialize({
    favfruit: "apple",
    data: {
        name: 'js',
        points: [1, 2, 3]
    }
}));

Upvotes: 2

Quentin
Quentin

Reputation: 944443

The param method will generate a query string for you, but you will need to to remove the existing query string.

var base = "http://example.com/foo/?example=old";
var data = {
  foo: "hello",
  bar: "world?"
};
var url = base.replace(/\?.*$/, "") + "?" + jQuery.param(data);
alert(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions