jQuery append params to url

ajax, javascript, jquery, param, url

Solution

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.

Problem

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!

Original source

Related problems