Misc Param
## jQuery Miscellaneous: `$.param()` Method
The `$.param()` method is a built-in utility in jQuery used to create a serialized representation of an array or an object.
This serialized value is formatted as a query string, making it ideal for use in the URL of AJAX requests or when sending data to a server.
---
## Syntax and Usage
The `$.param()` method converts key-value pairs from an object or array into a URI-encoded query string.
### Syntax
```javascript
$.param(object, trad)
```
### Parameter Values
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `object` | Array / Object | **Required.** Specifies the array or object to be serialized. |
| `trad` | Boolean | **Optional.** A boolean value specifying whether to use the traditional style of param serialization. Defaults to `false`. |
---
## How It Works: Deep vs. Traditional Serialization
By default, `$.param()` performs deep serialization to accommodate modern web frameworks (like Ruby on Rails or PHP) that can parse nested arrays and objects.
If you pass `{ a: [1, 2] }`, it will be serialized as `a[]=1&a[]=2` by default. If you set the `trad` parameter to `true`, it will use the traditional serialization style, resulting in `a=1&a=2`.
---
## Code Examples
### Example 1: Basic Object Serialization
This example demonstrates how to serialize a simple flat object into a query string when a button is clicked.
```html
```
**Output after clicking the button:**
```text
firstName=John&lastName=Doe&age=30
```
---
### Example 2: Deep Serialization vs. Traditional Serialization
This example highlights the difference between setting the `trad` parameter to `false` (default) and `true` when dealing with nested arrays.
```javascript
var data = {
colors: ["red", "green", "blue"]
};
// 1. Modern/Deep Serialization (Default)
var defaultSerialization = $.param(data);
console.log(defaultSerialization);
// Output: colors%5B%5D=red&colors%5B%5D=green&colors%5B%5D=blue
// Decoded: colors[]=red&colors[]=green&colors[]=blue
// 2. Traditional Serialization
var traditionalSerialization = $.param(data, true);
console.log(traditionalSerialization);
// Output: colors=red&colors=green&colors=blue
```
---
## Technical Considerations
1. **URL Encoding:** The `$.param()` method automatically performs URL encoding (using `encodeURIComponent`) on both keys and values to ensure the output is a valid URI query string.
2. **Form Serialization:** If you want to serialize an entire HTML form directly, consider using the `.serialize()` or `.serializeArray()` methods instead, which are designed specifically to work on jQuery form element collections.
3. **Recursive Handling:** When serializing nested objects, `$.param()` recursively serializes the properties to represent the deep data structure. Ensure your backend parser is configured to handle nested bracket notation (e.g., `user=John`) if you do not use the `trad` flag.
YouTip