or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-requests.mdindex.mdjquery-compat.mdpromise-interface.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Comprehensive form handling and data serialization utilities for converting form elements to various formats, processing query strings, and managing request data. These utilities work independently of the main request functions and are available as static methods on the reqwest object.

3

4

## Capabilities

5

6

### Form Serialization

7

8

Serializes form elements to various formats (query strings, objects, arrays) with flexible configuration options.

9

10

```javascript { .api }

11

/**

12

* Serializes form elements to various formats

13

* @param {Element|NodeList|Array} elements - Form elements to serialize

14

* @param {Object} options - Serialization options

15

* @returns {string|Object|Array} Serialized data in requested format

16

*/

17

reqwest.serialize(elements, options);

18

19

interface SerializeOptions {

20

type?: string; // 'map' | 'array' | undefined (query string)

21

}

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

// Query string format (default)

28

const form = document.getElementById('myform');

29

const queryString = reqwest.serialize(form);

30

// Result: "name=John&email=john@example.com&age=25"

31

32

// Object format

33

const dataObject = reqwest.serialize(form, {type: 'map'});

34

// Result: { name: "John", email: "john@example.com", age: "25" }

35

36

// Array format

37

const dataArray = reqwest.serialize(form, {type: 'array'});

38

// Result: [

39

// { name: "name", value: "John" },

40

// { name: "email", value: "john@example.com" },

41

// { name: "age", value: "25" }

42

// ]

43

44

// Serialize specific elements

45

const inputs = document.querySelectorAll('input[type=text]');

46

const textData = reqwest.serialize(inputs);

47

48

// Serialize mixed element types

49

const elements = [

50

document.getElementById('name'),

51

document.getElementById('email'),

52

document.querySelector('select[name=country]')

53

];

54

const mixedData = reqwest.serialize(elements, {type: 'map'});

55

```

56

57

### Serialize Array

58

59

Serializes form elements to an array of name/value pairs, providing a normalized format for form data.

60

61

```javascript { .api }

62

/**

63

* Serializes form elements to array of name/value pairs

64

* @param {Element|NodeList|Array} elements - Form elements to serialize

65

* @returns {Array} Array of {name, value} objects

66

*/

67

reqwest.serializeArray(elements);

68

```

69

70

**Usage Examples:**

71

72

```javascript

73

// Serialize entire form

74

const form = document.getElementById('registrationForm');

75

const formArray = reqwest.serializeArray(form);

76

// Result: [

77

// { name: "username", value: "alice" },

78

// { name: "email", value: "alice@example.com" },

79

// { name: "newsletter", value: "on" }

80

// ]

81

82

// Process array data

83

formArray.forEach(function(field) {

84

console.log(`Field ${field.name}: ${field.value}`);

85

});

86

87

// Convert to object if needed

88

const formObject = {};

89

reqwest.serializeArray(form).forEach(function(field) {

90

formObject[field.name] = field.value;

91

});

92

93

// Filter specific fields

94

const emailFields = reqwest.serializeArray(form)

95

.filter(field => field.name.includes('email'));

96

```

97

98

### Query String Conversion

99

100

Converts JavaScript objects to URL query strings with support for nested objects and array serialization.

101

102

```javascript { .api }

103

/**

104

* Converts object to URL query string

105

* @param {Object} object - Data object to serialize

106

* @param {boolean} traditional - Use traditional array serialization

107

* @returns {string} URL query string

108

*/

109

reqwest.toQueryString(object, traditional);

110

```

111

112

**Usage Examples:**

113

114

```javascript

115

// Simple object

116

const data = { name: 'John', age: 30, active: true };

117

const query = reqwest.toQueryString(data);

118

// Result: "name=John&age=30&active=true"

119

120

// Object with arrays (modern style, default)

121

const searchData = {

122

query: 'javascript',

123

tags: ['tutorial', 'beginner', 'web'],

124

author: 'john'

125

};

126

const modernQuery = reqwest.toQueryString(searchData);

127

// Result: "query=javascript&tags[]=tutorial&tags[]=beginner&tags[]=web&author=john"

128

129

// Object with arrays (traditional style)

130

const traditionalQuery = reqwest.toQueryString(searchData, true);

131

// Result: "query=javascript&tags=tutorial&tags=beginner&tags=web&author=john"

132

133

// Nested objects

134

const complexData = {

135

user: {

136

name: 'Alice',

137

profile: {

138

age: 25,

139

city: 'New York'

140

}

141

},

142

preferences: ['email', 'sms']

143

};

144

const nestedQuery = reqwest.toQueryString(complexData);

145

// Result: "user[name]=Alice&user[profile][age]=25&user[profile][city]=New%20York&preferences[]=email&preferences[]=sms"

146

147

// Use in requests

148

reqwest({

149

url: '/api/search?' + reqwest.toQueryString({

150

q: 'javascript frameworks',

151

limit: 10,

152

sort: 'relevance'

153

}),

154

success: function(results) {

155

console.log('Search results:', results);

156

}

157

});

158

```

159

160

### JSONP Callback Prefix

161

162

Gets the callback prefix used for generating unique JSONP callback function names.

163

164

```javascript { .api }

165

/**

166

* Gets the JSONP callback prefix used for generating callback names

167

* @returns {string} Callback prefix string used for JSONP requests

168

*/

169

reqwest.getcallbackPrefix();

170

```

171

172

**Usage Examples:**

173

174

```javascript

175

// Get the current callback prefix

176

const prefix = reqwest.getcallbackPrefix();

177

console.log('Callback prefix:', prefix);

178

// Result: "reqwest_1234567890123" (includes timestamp)

179

180

// Understanding JSONP callback naming

181

reqwest({

182

url: '/api/data',

183

type: 'jsonp',

184

jsonpCallback: 'callback'

185

});

186

// This will generate a callback function named something like:

187

// reqwest_1234567890123_0, reqwest_1234567890123_1, etc.

188

189

// For debugging JSONP requests

190

function debugJsonpRequest(url) {

191

const prefix = reqwest.getcallbackPrefix();

192

console.log('JSONP requests will use prefix:', prefix);

193

194

reqwest({

195

url: url,

196

type: 'jsonp',

197

success: function(data) {

198

console.log('JSONP callback executed successfully');

199

}

200

});

201

}

202

```

203

204

## Ender Framework Integration

205

206

When used with the Ender framework, these utilities are available as jQuery-style methods:

207

208

### Ender Serialize Methods

209

210

```javascript { .api }

211

// Available when reqwest is used with Ender

212

$.serialize(elements, options); // Alias for reqwest.serialize

213

$.serializeArray(elements); // Alias for reqwest.serializeArray

214

$.toQueryString(object, traditional); // Alias for reqwest.toQueryString

215

216

// jQuery-style element methods

217

$(form).serialize(); // Serialize form as query string

218

$(form).serialize({type: 'array'}); // Serialize form as array

219

$(form).serialize({type: 'map'}); // Serialize form as object

220

$(form).serializeArray(); // Serialize form as array

221

```

222

223

**Usage Examples with Ender:**

224

225

```javascript

226

// Form serialization

227

$('#contactForm').serialize(); // Query string

228

$('#contactForm').serialize({type: 'map'}); // Object

229

$('#contactForm').serializeArray(); // Array

230

231

// Specific element selection

232

$('input[type=text], select').serialize({type: 'map'});

233

$('#myform input[name=categories]').serialize({type: 'map'})['categories'];

234

235

// Object to query string

236

$.toQueryString({

237

search: 'ajax library',

238

category: 'javascript',

239

tags: ['xhr', 'promises']

240

});

241

```

242

243

## Practical Use Cases

244

245

### Form Submission

246

247

```javascript

248

// Traditional form submission

249

const form = document.getElementById('userForm');

250

form.addEventListener('submit', function(e) {

251

e.preventDefault();

252

253

reqwest({

254

url: '/api/users',

255

method: 'POST',

256

data: reqwest.serialize(form, {type: 'map'}),

257

success: function(response) {

258

console.log('User created:', response);

259

}

260

});

261

});

262

263

// Dynamic form validation

264

const formData = reqwest.serializeArray(form);

265

const errors = [];

266

267

formData.forEach(function(field) {

268

if (field.name === 'email' && !field.value.includes('@')) {

269

errors.push('Invalid email format');

270

}

271

if (field.name === 'age' && parseInt(field.value) < 18) {

272

errors.push('Must be 18 or older');

273

}

274

});

275

```

276

277

### URL Construction

278

279

```javascript

280

// Build search URLs

281

function buildSearchUrl(baseUrl, filters) {

282

const queryString = reqwest.toQueryString(filters);

283

return baseUrl + (queryString ? '?' + queryString : '');

284

}

285

286

const searchUrl = buildSearchUrl('/api/products', {

287

category: 'electronics',

288

price_min: 100,

289

price_max: 500,

290

brands: ['Apple', 'Samsung'],

291

in_stock: true

292

});

293

// Result: "/api/products?category=electronics&price_min=100&price_max=500&brands[]=Apple&brands[]=Samsung&in_stock=true"

294

295

// Pagination URLs

296

function buildPaginationUrl(baseUrl, currentParams, page) {

297

const params = Object.assign({}, currentParams, { page: page });

298

return baseUrl + '?' + reqwest.toQueryString(params);

299

}

300

```

301

302

### Data Processing

303

304

```javascript

305

// Convert form data for API

306

function processFormForApi(form) {

307

const formArray = reqwest.serializeArray(form);

308

const processedData = {};

309

310

formArray.forEach(function(field) {

311

// Convert numeric strings to numbers

312

if (field.name.includes('_number') || field.name === 'age') {

313

processedData[field.name] = parseInt(field.value);

314

}

315

// Convert boolean strings

316

else if (field.value === 'true' || field.value === 'false') {

317

processedData[field.name] = field.value === 'true';

318

}

319

// Handle arrays (checkboxes, multi-selects)

320

else if (processedData[field.name]) {

321

if (!Array.isArray(processedData[field.name])) {

322

processedData[field.name] = [processedData[field.name]];

323

}

324

processedData[field.name].push(field.value);

325

}

326

else {

327

processedData[field.name] = field.value;

328

}

329

});

330

331

return processedData;

332

}

333

334

// Use processed data in request

335

const form = document.getElementById('advancedForm');

336

const apiData = processFormForApi(form);

337

338

reqwest({

339

url: '/api/advanced-endpoint',

340

method: 'POST',

341

data: apiData,

342

success: function(response) {

343

console.log('Processed data submitted:', response);

344

}

345

});

346

```

347

348

### Cross-Browser Form Handling

349

350

```javascript

351

// Handle various form element types

352

function getFormElements(form) {

353

const elements = [];

354

355

// Modern browsers

356

if (form.elements) {

357

return Array.from(form.elements);

358

}

359

360

// Legacy browser support

361

const inputs = form.getElementsByTagName('input');

362

const selects = form.getElementsByTagName('select');

363

const textareas = form.getElementsByTagName('textarea');

364

365

for (let i = 0; i < inputs.length; i++) elements.push(inputs[i]);

366

for (let i = 0; i < selects.length; i++) elements.push(selects[i]);

367

for (let i = 0; i < textareas.length; i++) elements.push(textareas[i]);

368

369

return elements;

370

}

371

372

// Use with reqwest utilities

373

const form = document.getElementById('compatForm');

374

const elements = getFormElements(form);

375

const serializedData = reqwest.serialize(elements, {type: 'map'});

376

```