• 0

Transmit an array of strings in a POST operation using Jquery/AJAX


Question

Hello! I would like to submit an array of strings from a web form to my web service and need a little bit of hand holding. My web service I've written seems fine with having an array of strings as input but I'm not exactly sure how to encode this in javascript from my html form elements before I ship the data to my web service to be processed. The array of strings will be pretty small (on the order of 20x3 strings).

I suspect that there is a clever way to do this by coding the form correctly and just running a jquery .serialize() operation on the form and submitting it.

My first thought was to define a number of textbox inputs and give them incremental ID#'s such as "array0_0", "array0_1", "array0_2", "array1_0", "array1_1", "array_1_2", "array_2_1" etc.

Then as a first step before submitting the post, collect all the values in the textboxs and compile an array using 2 nested for loops. Something like that would probably work, but I was wondering if there was some magic that I could do in my form so that jquery recognizes an array of strings in my form so that the .serialize() function just does its magic.

Thanks!

-Shad

21 answers to this question

Recommended Posts

  • 0

Maybe use JSON to convert it back and forth as needed? That's how we do search suggestions on our website. A service serializes JSON, the ajax (jquery, really) javascript picks it up and parses it and displays the results.

  • 0

To be more specific... we have a series of services on one server... including a search service. When you type in a search box a javascript function sends off queries to the server (the web app action written to deal with this) which then queries the service. The service hands back the JSON response, all the action does is reads it as an input buffer and println's it out to the client. Once the javascript gets the response back it parses it and displays the result.

UI (javascript) --> Action (java) --> SERVICE (java) --> Action (java) --> UI (javascript)

  • 0


var arrayToStore = new Array();
var $strings = $('form input');
$strings.each(function(){
arrayToStore.push(this.val());
})
[/CODE]

Also, if you want to store them with a specific key, give them all a data-something attribute rather than abusing the ID property.

  • 0


var arrayToStore = new Array();
var $strings = $('form input');
$strings.each(function(){
arrayToStore.push(this.val());
})
[/CODE]

Also, if you want to store them with a specific key, give them all a data-something attribute rather than abusing the ID property.

I thought that it was only considered "abuse" if you don't use unique IDs.

Your solution is a good start but I need to make a 2d string array in the end so I'll need to tweak it.

  • 0

I have some ideas to play around with. Haha, its funny how much time is spent just communicating between applications and services. This particular application started as a standalone windows program, but my boss wants tighter control so now I'm extending it with a web front end. I think I've spent more time trying to figure out jquery and javascript than I did with the whole write up of my application. I guess whatever you are use to is easy, its when you are up against a learning curve that makes things hard.

Still, I'm amazed at how powerful this jquery and AJAX stuff is and how far the tools have come in the past 10 years. When I was doing full time web development I did everything in server side PHP scripting with auxiliary basic javascript stuff. Using AJAX has the huge advantage of not having to redraw the whole page for every little thing. Now it seems like it is better to offload as much work on the client side as you can and just write auxiliary server side scripting.

  • 0

I thought that it was only considered "abuse" if you don't use unique IDs.

Your solution is a good start but I need to make a 2d string array in the end so I'll need to tweak it.

It's not abuse, per se, but if you can use the data- attribute, it makes much more sense to use it in a case like this. If you gave them all some data-location1 and data-location2 attribute (or however named), as you iterate through with each you can grab those attributes using .attr(), and then store the final string in your 2d array.

  • 0

It's not abuse, per se, but if you can use the data- attribute, it makes much more sense to use it in a case like this. If you gave them all some data-location1 and data-location2 attribute (or however named), as you iterate through with each you can grab those attributes using .attr(), and then store the final string in your 2d array.

Word. Thanks.

  • 0


(function store(){
var arrayToStore = [['',''],['','']];
var $strings = $('form input');
$strings.each(function(){
var x = $(this).attr('data-loc1');
var y = $(this).attr('data-loc2');
arrayToStore[x][y] = $(this).val();
});
console.log(arrayToStore);
})();
[/CODE]

A better example...

  • 0

I keep getting an error when I try to use multidimensional arrays.

Here is my form:

<form>
	<table>
		<tr>
			<th> </th>
			<th>Independent</th>
			<th>Pass</th>
			<th>Fail</th>
		</tr>
		<tr>
			<th>Data Labels</th>
			<td><input type="textbox" data-row="0" data-col="0" /></td>
			<td><input type="textbox" data-row="0" data-col="1" /></td>
			<td><input type="textbox" data-row="0" data-col="2" /></td>
		</tr>
		<tr>
			<th>Data Row 1</th>
			<td><input type="textbox" data-row="1" data-col="0" /></td>
			<td><input type="textbox" data-row="1" data-col="1" /></td>
			<td><input type="textbox" data-row="1" data-col="2" /></td>
		</tr>
		<tr>
			<th>Data Row 2</th>
			<td><input type="textbox" data-row="2" data-col="0" /></td>
			<td><input type="textbox" data-row="2" data-col="1" /></td>
			<td><input type="textbox" data-row="2" data-col="2" /></td>
		</tr>

		</table>
	</form>
	<p><input type="button" value="Run Regression" onClick="ProcessButtonClick()"/></p>

Here is my javascript:

   	 function ProcessButtonClick() {
			var arrayToStore = [['',''],['','']];
			var $strings = $('form input');
			$strings.each(function(){
				var x = parseInt($(this).attr('data-row'));
				var y = parseInt($(this).attr('data-col'));
				arrayToStore[x][y] = $(this).val();
			});
			console.log(arrayToStore);
}

I get this error in the console from Firebug:

TypeError: can't convert undefined to object

arrayToStore[x][y] = $(this).val();

If I'm only addressing 1 index, it works (i.e., arrayToStore[x] = $(this).val(); does not give me an error but doesn't give me the right output obviously).

Thank you for your input and time.

  • 0

Its an array initialization problem... once I sized it correctly when dimensioning the array variable it worked fine:

var arrayToStore = [['','',''],['','',''],['','','']]

I did not think that Javascript arrays had to be strictly dimensioned... Is there a short hand for this? I would think new Array(3,3) or something would look better...

  • 0

#

# CORRECT WAY TO INSTANTIATE AN ARRAY WITHOUT DIMENSION

#

var arrayToStore = [];

#

# PROBLEM

#

var arrayToStore = [['',''],['','']];

#

# REASON

#

IF you instantiate the array with only the above "problem" dimensions and do not correct the length beyond this, they will be truncated.

  • 0

Its an array initialization problem... once I sized it correctly when dimensioning the array variable it worked fine:

var arrayToStore = [['','',''],['','',''],['','','']]

I did not think that Javascript arrays had to be strictly dimensioned... Is there a short hand for this? I would think new Array(3,3) or something would look better...

I had worked that code up in a fiddle and was getting the same error, hence why I posted it with ['','']. The general consensus seems to be to create a helper fuction that, given a number x, can push x number of blank objects into the array which you can then fill.

Or... just use an object. It's certainly the preferred way in JS unless you really need an array of arrays.

#

# CORRECT WAY TO INSTANTIATE AN ARRAY WITHOUT DIMENSION

#

var arrayToStore = [];

#

# PROBLEM

#

var arrayToStore = [['',''],['','']];

#

# REASON

#

IF you instantiate the array with only the above "problem" dimensions and do not correct the length beyond this, they will be truncated.

If you do arrayToStore = [] and then try to set arrayToStore[0][0] = something, you'll get the same error.

  • 0

If you gave me an example of how you would like the content it might make it easier but off the top of my mind - how does this work?


var arrayData = [];

function ProcessButtonClick() {

var $strings = $('form input');

$strings.each(function(){

var arrayParent = [];
var arrayChild = [];

var x = parseInt($(this).attr('data-row'));
var y = parseInt($(this).attr('data-col'));

arrayChild[x] = $(this).val();
arrayParent[y].push(arrayChild);
arrayData.push(arrayParent)

});



}
[/CODE]

  • 0

tim_s - I get this error:

TypeError: arrayParent[y] is undefined

arrayParent[y].push(arrayChild);

Seems like the only way for me to get it to work is to declare the full size of the array... in just about every language you can initialize the size of an array directly but for some reason this doesn't seem possible in Javascript unless I'm missing something.

In the end, the size of my table is fixed so dimensioning out the variable before hand is fine.

  • 0

Seems like the only way for me to get it to work is to declare the full size of the array... in just about every language you can initialize the size of an array directly but for some reason this doesn't seem possible in Javascript unless I'm missing something.

In the end, the size of my table is fixed so dimensioning out the variable before hand is fine.

You're not, as I mentioned, it's not a preferred way of doing things in JS. If you must, this will work:


<script>
var multidArray = function(y){
var array = [];
for(i=0;i<y;i++){
array.push(['example', 'array']);
}
return array;
}
var newArray = multidArray(6);
newArray[1][0] = ['now', 1,1];
newArray[1][1] = 'modified';
console.log(newArray);
</script>
[/CODE]

However, in JS, this is preferable:

[CODE]
var better = {};
better[0] = {1: 'this', 2 : 'will', 3: 'work', 4: 'much', 5: 'better'};
console.log(better[0][1]); // will log 'this'
[/CODE]

  • 0

Well..its all moot because I can't get the input array into my web service.... apparently arrays of strings are a supported output (in JSON format) but not a supported input. I'll have to turn my table into CSV and then program my web service accordingly.

This topic is now closed to further replies.
  • Posts

    • Internet Download Manager (IDM) 6.43 Build 1 by Razvan Serea Internet Download Manager (IDM) is a tool to increase download speeds by up to 8 times due to its smart dynamic file segmentation technology. Unlike other download managers and accelerators, Internet Download Manager segments downloaded files dynamically during download process, and it reuses available connections without additional connect and login stages to achieve the best possible acceleration performance. Comprehensive error recovery and resume capability will restart broken or interrupted downloads due to lost connections, network problems, computer shutdowns, or unexpected power outages. All popular browsers are supported IDM integrates seamlessly into Google Chrome, FireFox, Microsoft Edge, Opera, Safari, Internet Explorer, Maxthon and all other popular browsers to automatically handle your downloads. You can also drag and drop files, or use Internet Download Manager from command line. The program supports proxy servers, ftp and http protocols, firewalls, redirects, cookies, authorization, MP3 audio and video content processing. IDM includes web site spider and grabber IDM downloads all required files that are specified with filters from web sites, for example all pictures from a web site, or subsets of web sites, or complete web sites for offline browsing. It's possible to schedule multiple grabber projects to run them once at a specified time, stop them at a specified time, or run periodically to synchronize changes. Easy downloading with one click When you click on a download link in a browser, IDM will take over the download and accelerate it. You don't need to do anything special, just browse the Internet as you usually do. IDM will catch your downloads and accelerate them. IDM supports HTTP, FTP, HTTPS and MMS protocols. Changes in Internet Download Manager 6.43 Build 1: Added the ability to download MP4 files from web sites where previously only TS videos were available. IDM displays both TS and MP4 file formats in its video download button. If you only need MP4 files, disable TS in IDM Options -> General tab -> Customize IDM Download panels in browsers -> Edit button. Remove TS extension on "Customize IDM Download panel in browsres" dialog Fixed video downloading problems on several popular web sites Fixed bugs Download: Internet Download Manager 6.43 Build 1 | 11.9 MB (Shareware) Links: Internet Download Manager Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • This is of course "clickbait" WTF? It is literally your example but tech based. A "clickbait" title is a sensationalized headline designed to manipulate readers into clicking a link using things like "fear" rather than delivering objective facts. A "clickbait" headline also usually provides little value compared to the hype generated. How does this headline not qualify? It's a generic often reused headline that is overly sensationalized. Oh no! "millions" can't use this app anymore. It has no basic facts like what f*cking app. You read the article and it's the Samsung VPN which no one cares about and there is a million free VPNs. How are you defending this ######? Headlines like this (and among other things) make me read Neowin much less than I used to in the past. It's trash...
    • UniGetUI 2026.2.1 by Razvan Serea UniGetUI is an application whose main goal is to create an intuitive GUI for the most common CLI package managers for Windows 10 and Windows 11, such as Winget, Scoop and Chocolatey. With UniGetUI, you'll be able to download, install, update and uninstall any software that's published on the supported package managers — and so much more. UniGetUI features Install, update and remove software from your system easily at one click: UniGetUI combines the packages from the most used package managers for windows: WinGet, Chocolatey, Scoop, Pip, Npm and .NET Tool. Discover new packages and filter them to easily find the package you want. View detailed metadata about any package before installing it. Get the direct download URL or the name of the publisher, as well as the size of the download. Easily bulk-install, update or uninstall multiple packages at once selecting multiple packages before performing an operation Automatically update packages, or be notified when updates become available. Skip versions or completely ignore updates in a per-package basis. Manage your available updates at the touch of a button from the Widgets pane or from Dev Home pane with UniGetUI Widgets. The system tray icon will also show the available updates and installed package, to efficiently update a program or remove a package from your system. Easily customize how and where packages are installed. Select different installation options and switches for each package. Install an older version or force to install a 32bit architecture. [But don't worry, those options will be saved for future updates for this package] Share packages with your friends to show them off that program you found. Here is an example: Hey @friend, Check out this program! Export custom lists of packages to then import them to another machine and install those packages with previously-specified, custom installation parameters. Setting up machines or configuring a specific software setup has never been easier. Backup your packages to a local file to easily recover your setup in a matter of seconds when migrating to a new machine Devolutions UniGetUI 2026.2.1 changelog: This release brings several quality-of-life improvements, new troubleshooting features, privacy enhancements, and a collection of fixes and stability improvements across UniGetUI. New Features Added an operation counter to provide better visibility into ongoing package operations. Added a setting to automatically redact usernames from exported logs, making it easier to share diagnostic information while protecting personal data. UniGetUI now opens the release notes page after updating by default, helping users discover new features, improvements, and fixes. This behavior can be disabled from Settings. Expanded diagnostics and troubleshooting capabilities to simplify issue reporting and support. Improvements Improved update reliability and handling of update-related edge cases. Enhanced installer behavior when updating running UniGetUI instances. Improved package manager integrations and package metadata processing. Refined various user interface elements for a more consistent experience. Updated package screenshots, icons, and bundled resources. Improved logging and error reporting throughout the application. Bug Fixes Fixed multiple issues affecting application updates and self-update workflows. Resolved several package installation and upgrade edge cases. Fixed UI inconsistencies and unexpected behaviors across different pages. Improved handling of package manager responses and failure scenarios. Addressed issues affecting package discovery and metadata retrieval. Fixed a number of stability issues reported by the community. Performance & Stability Improved overall application stability during package operations. Reduced the likelihood of update interruptions and inconsistent update states. Various reliability and performance optimizations across the codebase. Download: UniGetUI 64-bit | Portable | ~200.0 MB (Open Source) Download: UniGetUI ARM64 | Portable Links: UniGetUI Home Page | GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • PDF4QT 1.6.0.0 by Razvan Serea PDF4QT is a free and open-source application created to provide a complete solution for working with PDF documents in a simple, flexible, and effective way. It offers all the essential tools you need to handle your files: you can view PDFs with smooth navigation, edit content, annotate pages, and highlight key sections for better collaboration. It also allows you to compare two versions of a document, making it easy to spot changes. Built-in security features give you control over protecting sensitive information and managing access. Applications PDF4QT Viewer Profi: Advanced PDF browsing with encryption, digital signature verification, annotation editing, regex text search, page-to-image conversion, and plugin support. PDF4QT Viewer Lite: Lightweight viewer with essential, user-friendly PDF viewing functions. PDF4QT DocPage Organizer: Merge, split, move, clone, or add pages easily with an intuitive interface. PDF4QT DocDiff: Compare two PDFs, highlight differences page-to-page, and export results to XML. Key Features Multithreading Support for faster PDF processing Hardware Accelerated Rendering for smooth, high-quality display Encryption to secure documents Color Management to preserve accurate color profiles Optional Content Handling to control visibility of content Text Layout Analysis for better text extraction and editing Signature Validation for verifying digital signatures Annotations and Form Filling for interactivity Text-to-Speech Conversion to listen to PDFs Advanced Annotation Tools (images, text, etc.) File Attachments Management to view and save attachments Optimization to reduce file size without losing quality Command Line Tool for automation Audio Book Conversion from PDFs Internal Structure Inspector to explore PDF structure Compare Documents to detect differences Redaction to remove sensitive information Document Signing for digital authentication PDF4QT 1.6.0.0 release notes: PDF4QT 1.6.0.0 brings a major image compression and optimization update, especially for PageMaster and assembled output documents. Image compression is now integrated into the assembly/export workflow, backed by new optimizer infrastructure, UI controls, feedback fixes, and tests. This should make PageMaster much more useful for producing smaller output PDFs directly from assembled or reorganized documents. The release also contains a large PageMaster refresh with improved drag and drop, recent files, crop pages, save/restore functionality, rotation and size indicators, a reworked icon set, and faster output preview rendering. Viewer and Editor workflows were improved with wildcard Advanced Find, Enter-to-search behavior, better outline keyboard selection, startup settings, fullscreen support, side-to-side scrolling, smoother scrolling, text selection, snapping, and expanded annotation controls. Compatibility and platform behavior were improved as well, including fixes for embedded files, fonts, checkboxes, invisible text, menu colors, highlights, XMP metadata, Windows color management, AppImage packaging, MSIX generation, installer behavior, translations, and newer compiler/Qt warnings. The commit history also includes a new scan-and-edit plugin foundation and color management performance work. Changelog: Highlights Image compression for PageMaster / DocPage Organizer and assembled output documents (#92) Major PageMaster UX refresh, including drag and drop, recent files, crop pages, save/restore, icons, and output preview performance (#383, #18) Improved image optimization feedback, including final resolution and DPI updates (#384) Better Viewer and Editor navigation: fullscreen, side-to-side scrolling, smoother scrolling, text selection, snapping, and outline keyboard selection (#242, #368, #136, #321, #250, #373) Advanced Find wildcard mode and Enter-to-search behavior (#379, #378) PDF compatibility fixes for embedded files, fonts, checkboxes, invisible text, form content suppression, and Windows color management (#225, #356, #256, #230, #326, #224, #385, #388) Startup settings, custom settings directory support, Linux double-click viewer separation, and packaging/build fixes (#382, #380, #381) Scan-and-edit plugin foundation and broader translation updates from the 1.6.0.0 development cycle Resolved Issues Issue #389: Adding hyperlink to internal object in PDF Issue #388: Update Windows color management system Issue #385: PDFTextLayoutGenerator::isContentKindSuppressed(ContentKind kind) is missing ContentKind::Form Issue #384: In the "Optimize Images" dialog, the info on the final image resolution and final DPI does not update Issue #383: UX improvements for PDF4QT PageMaster tool (v1.5.3.1) (ex. DocPage Organizer) Issue #382: Startup Settings Issue #381: Separated apps for double-click viewer in Linux Issue #380: Ability to run app with custom settings directory - executable parameter with path Issue #379: Advanced Find - Wildcard Mode Issue #378: Advanced Find - Should start searching if Enter key is pressed Issue #376: Deleting a note jumps to Outline Issue #375: Not enough maximum compiled page cache Issue #373: Ctrl/Shift keyboard selection for Outline Issue #372: Option to not color images Issue #370: Extracting pages within a range Issue #369: Keeping redact box on Issue #368: Side-to-side scrolling Issue #357: Bulk delete/add/edit of page labels Issue #356: Compatibility issues - font problems Issue #354: Color blend mode for highlights Issue #352: Icon size of the sidebar Issue #349: Add inherit zoom to bookmark zoom options Issue #338: Editor toolbox higher than editor window Issue #334: Impossible to set French language Issue #326: Checkboxes don't render in PDF4QT Issue #324: Menu text not rendered with correct color Issue #321: Select text in Viewer Issue #291: Support for editing XMP metadata or exporting to PDF/UA format Issue #282: Editor outline view: always zooms to around 50% Issue #256: PDF4QT cannot show some specific fonts correctly Issue #253: Undo/redo doesn't work in "edit page content" mode Issue #250: Snapping Issue #242: Full screen Issue #234: Setting font, font size and area of text annotations Issue #230: Garbled characters when opening PDF files with PDF4QT Issue #225: PDF4QT cannot open PDF files with embedded files Issue #224: Option to remove invisible text Issue #194: Change page size Issue #160: Color | Custom (green/black) does not work Issue #136: Smooth scrolling of document with mouse middle wheel - flywheel Issue #92: Add image compression to PDF DocPage Organizer Issue #18: Performance optimization - OutputPreview Renderer Download: PDF4QT 1.6.0.0 | Portable | ~30.0 MB (Open Source) Download: PDF4QT MSIX | 29.4 MB Links: PDF4QT Home Page | PDF4QT @GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Veteran
      branfont went up a rank
      Veteran
    • Reacting Well
      Almohandis earned a badge
      Reacting Well
    • First Post
      Cosminus earned a badge
      First Post
    • One Year In
      ThatGuyOnline earned a badge
      One Year In
    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      472
    2. 2
      +Edouard
      181
    3. 3
      PsYcHoKiLLa
      120
    4. 4
      Steven P.
      85
    5. 5
      neufuse
      73
  • Tell a friend

    Love Neowin? Tell a friend!