» Javascript equivalent for PHP's http_build_query

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: http_build_query.

PHP http_build_query

Description

http_build_query - Generate URL-encoded query string

string http_build_query( array formdata [, string numeric_prefix [, string arg_separator]] )

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

  • formdata

    May be an array or object containing properties.

    The array form may be a simple one-dimensional structure, or an array of arrays (who in turn may contain other arrays).

  • numeric_prefix

    If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

    This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

  • arg_separator

    arg_separator.output is used to separate arguments, unless this parameter is specified, and is then used.

Return Values

Returns a URL-encoded string.

See Also

Javascript http_build_query

Source

This is the main source of the Javascript version of PHP's http_build_query

function http_build_query( formdata, numeric_prefix, arg_separator ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://crestidg.com)
    // *     example 1: http_build_query({ foo: 'bar', baz: 'boom', cow: 'milk', php: 'hypertext processor' }, '', '&');
    // *     returns 1: 'foo=bar&baz=boom&cow=milk&php=hypertext+processor'
    // *     example 2: http_build_query({0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', cow: 'milk', php :'hypertext processor'}, 'myvar_');
    // *     returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor'
 
    var key, use_val, use_key, i = 0, tmp_arr = [];
 
    if(!arg_separator){
        arg_separator = '&';
    }
 
    for(key in formdata){
        use_key = encodeURIComponent(key);
        use_val = encodeURIComponent((formdata[key].toString()));
        use_val = use_val.replace(/%20/g, '+');
 
        if(numeric_prefix && !isNaN(key)){
            use_key = numeric_prefix + i;
        }
        tmp_arr[i] = use_key + '=' + use_val;
        i++;
    }
 
    return tmp_arr.join(arg_separator);
}

Examples

Currently there are 2 examples

Example 1

This is how you could call http_build_query()
http_build_query({ foo: 'bar', baz: 'boom', cow: 'milk', php: 'hypertext processor' }, '', '&');
And that would return
'foo=bar&baz=boom&cow=milk&php=hypertext+processor'

Example 2

This is how you could call http_build_query()
http_build_query({0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', cow: 'milk', php :'hypertext processor'}, 'myvar_');
And that would return
'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor'

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript, phpjs
category: Programming - Javascript - PHP equivalents
read: 495 times

Add comment

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#13. Kevin on 15 March 2008

Kevin@ Michael White: Thanks for bringing it to my attention, yeah your mail is quite big so I saved it for this weekend ;) I'll get back to you today or tomorrow, cheers

#12. Michael White on 14 March 2008

Michael WhiteNo problem. Did you get my email from a couple of days ago? Also, I left a bugfix on the print_r() function that doesn't seem to have been noticed yet.

#11. Kevin on 14 March 2008

Kevin@ Michael White: thanks for pointing that out Michael!

#10. Michael White on 14 March 2008

Michael WhiteWell I just found out that escape() is actually not the best thing to use for this function. encodeURIComponent() seems to be required here. The reason behind this is that a literal + sign does not get escaped by escape() and so gets "lost in translation" when working in PHP. I never would have discovered this if I had not been sending values that were either a + or - sign. I have no idea if there are any other characters affected by this at this time. My apologies to anyone who may be affected by this; I thought that escape() worked properly until now.

#9. Kevin on 03 March 2008

Kevin@ Michael White: fixed!

#8. Michael White on 02 March 2008

Michael WhiteOne more little note: Replace:

use_val = use_val.replace('%20', '+');
with:
use_val = use_val.replace(/%20/g, '+');
The original version only replaces a single instance of the string. Using the regular expression with /g at the end tells it to replace "globally" meaning every instance of %20 in the string. http://crestidg.com

#7. Kevin on 02 March 2008

Kevin@ Michael White: Done

#6. Michael White on 02 March 2008

Michael WhiteOoops - forgot the code block.... Replace....

use_key = encodeURIComponent(key);
use_val = encodeURIComponent(formdata[key].toString());
use_val = use_val.replace('%20', '+');
use_key = escape(key);
use_val = escape(formdata[key].toString());

#5. Michael White on 02 March 2008

Michael WhiteAh - I ran into that problem where the output of encodeURI was incompatible with PHP as well about two months ago.

You have to use escape() instead. PHP likes this one. I've used it for a while in my own Ajax requests.

#4. Kevin on 02 March 2008

Kevin@ marrtins: Thanks for contributing!

#3. Kevin on 02 March 2008

KevinLegaev Andrey: Thank you, still needed the

use_val = use_val.replace('%20', '+');
though, apparently encodeURIComponent does not produce php compatible encoded ouput

#2. Legaev Andrey on 02 March 2008

Legaev AndreyHi! Key can contain no-ascii character too, and encodeURIComponent() is more appropriate function. Please, replace code

use_key = key;
use_val = encodeURI(formdata[key].toString());
use_val = use_val.replace('%20', '+');
by following:
use_key = encodeURIComponent(key);
use_val = encodeURIComponent(formdata[key].toString());
Key can contain no-ascii character too, and encodeURIComponent() is more appropriate function.

#1. marrtins on 02 March 2008

marrtinsHello!

I got syntax errors on IE6:
const CASE_LOWER = 0;
const CASE_UPPER = 1;
... [more]
raplacing with
var CASE_LOWER = 0;
var CASE_UPPER = 1;

works fine