2

I currently have an associative array urlvalue with values as follows:

{"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"}

I would like to turn this array into a URL so that I can send the variables to another page. How can it be done using jquery so that they appear like this:

?folder=subscriber&file=setstatus&alert=yes&id=12

Thanks

1

7 Answers 7

8

You need jQuery.param():

var params = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var str = jQuery.param(params);
Sign up to request clarification or add additional context in comments.

Comments

4

Use the

$.param(VALUE)

funciton.

Example:

var obj = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"},
    toParam= $.param(obj);

alert(toParam);

output:

folder=subscriber&file=setstatus&alert=yes&id=12

Fillder: http://jsfiddle.net/BGjWT/

Comments

1

You can use the map method to turn each key-value pair into a string, then join the array of strings into a single string. Use the encodeURICompontent function to encode the keys and values correctly:

var urlvalue = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};

var param = '?' + $.map(urlvalue, function(v, k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');

alert(param);

Demo: http://jsfiddle.net/Guffa/sCn5U/

Comments

1

You can use the http_build_query() function:

http://phpjs.org/functions/http_build_query/

Comments

0

Try this:

var test = {"folder":"subscriber", "file":"setstatus", "alert":"yes", "id":"12"};
var queryString = "?folder=" + test.folder + "&file=" + test.file + "&alert=" + test.alert + "&id=" + test.id + "";
alert(queryString);

Fiddle

Comments

0

If you don't mind using a plugin, there are some nice ones that do the job.

Comments

0

Possible solution that does not involve jQuery at all (I assume people post jQuery solutions because of the tag):

var combine = function(params) {
    var lst = [];
    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            lst.push(encodeURIComponent(key)+"="+encodeURIComponent(params[key]));
        }
    }
    return "?"+lst.join("&");
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.