13

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!

Karolis
  • 2,580
  • 2
  • 16
  • 31

5 Answers5

7

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.

Karolis
  • 2,580
  • 2
  • 16
  • 31
3

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);
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
2

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]
    }
}));
Shreejibawa
  • 1,860
  • 1
  • 25
  • 35
  • 1
    `Uncaught ReferenceError: serialize is not defined` - and it looks like you are still reinventing the wheel, just differently. – Quentin Feb 20 '15 at 13:13
  • 1
    how is your `getQueryStr ` method different from jQuerys `$.param()`? My question was about adding arguments to an existing url which already contains a query string. `$.ajax()` method handles that very nicely. – Karolis Feb 20 '15 at 18:21
1

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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

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

Anupam
  • 14,950
  • 19
  • 67
  • 94