• 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
  On 21/02/2013 at 17:23, threetonesun said:


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
  On 21/02/2013 at 17:26, Shadrack said:

I'll try that. I found a JSON.stringify function but am not finding a serialize function.

I should look at the code... it probably isn't then, probably just a raw string being written.

  • 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
  On 21/02/2013 at 17:32, Shadrack said:

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
  On 21/02/2013 at 17:58, threetonesun said:

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:

  Quote

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
  On 21/02/2013 at 22:04, Shadrack said:

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.

  On 21/02/2013 at 22:08, tim_s said:

#

# 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:

  Quote

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
  On 21/02/2013 at 23:27, Shadrack said:

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

    • Trump announces a gold smartphone for $499 and new "T1 Mobile" 5G wireless service by Sagar Naresh Bhavsar The Trump Organization, spearheaded by President Trump's sons, Donald Trump Jr. and Eric Trump, has unveiled "T1 Mobile," a new mobile wireless service under the Trump Mobile brand. The service aims to offer affordable 5G services while competing with major telecom providers, with a patriotic twist. The announcement coincides with the 10th anniversary of Donald Trump's first presidential campaign launch. Trump Mobile is positioned as a wireless service that is meant to offer top-notch smartphone connectivity services for American people. One of the highlights of the wireless service plan is "The 47 Plan," priced at $47.45 per month, which gives a nod to Donald Trump being the 47th president of America. According to the official website, the plan includes: Unlimited talk time, messages, and internet Complete device protection 24/7 roadside assistance through Drive America Telehealth services, including virtual medical care, mental health support, and easy ordering and delivery for prescription medications Free International calling to more than 100 countries, including many with American military bases, to help honor the families who are bravely serving in our military abroad No contracts, no credit check Switching to Trump Mobile is simple. Customers would need to make a call to 888-TRUMP45, and they can continue using their current phone when making the transition. Trump Mobile has emphasized making customer support a top priority, promising 24/7 access to real representatives based in the U.S., no bots or automated systems. The company has claimed that T1 Mobile runs on the country's largest 5G networks, which will offer solid coverage across America. In addition to the mobile wireless service, Trump Mobile also announced its upcoming smartphone, the "T1 Phone," which will debut in September. It appears to feature a gold-colored metal case with an American flag etched on it, with triple cameras (iPhone knock-off). The company again highlighted that the device will be designed and built in America and is now available for pre-order.
    • OnePlus reveals five upcoming devices including the Nord 5 by David Uzondu OnePlus has confirmed that its next big product launch will take place on July 8 for its European and Indian markets. The company is dropping a whole slate of new hardware, announcing five different products. These include two new phones, the Nord 5 and its cheaper sibling, the Nord CE5, alongside a OnePlus Pad Lite, a smaller version of the OnePlus Watch 3, and a new pair of OnePlus Buds 4. The whole point of the Nord series, which originally launched back in 2020, has always been to filter some of the company's flagship tech down into phones that do not cost a fortune, and this year looks to be the most aggressive attempt at that yet. The star of this show is the OnePlus Nord 5. It is getting a huge performance upgrade, as it will be the first Nord phone to use a flagship-grade Qualcomm chip, the Snapdragon 8S Gen 3. That is a massive leap from the Snapdragon 7+ Gen 3 that powered the Nord 4 last year. OnePlus also seems serious about keeping it cool, adding an advanced 7,300mm² liquid cooling system and support for faster LPDDR5X RAM. The company even made a point to mention that the phone will handle games like Battlegrounds Mobile India at 90 to 144FPS. OnePlus is also making some interesting design changes. The company claimed that moving back to a vertical camera setup, a clear change from last year's Nord 4 and its horizontal bar, was a practical decision. The new layout supposedly optimizes internal space to fit the beefier chipset and other components. In another departure, the phone's frame will not be metal, unlike what we saw last year with the Nord 4. This change was based on feedback from a global survey where people apparently prioritized simple and practical designs over more premium materials. The Nord 5 will be available in a pale blue finish called "Dry Ice," while the cheaper Nord CE5 gets a "Marble Mist" color. Both new Nord phones will also replace the company's signature Alert Slider with a new customizable Plus Key. According to Celina Shi, CMO at OnePlus Europe, this is a "natural evolution" of the button, allowing it to be programmed for different actions like launching the camera or starting a recording. This key is tied to a new set of AI features called Plus Mind, which can recognize on-screen content and save it as a "memory." For example, it can pull schedule details from a picture of a flyer and add them directly to your calendar. The new Nord phones are joined by a handful of other devices. The OnePlus Watch 3 will now come in a smaller 43mm size for those with smaller wrists, and the company claims it has "exclusive monitoring features" not found on the larger model. The OnePlus Pad Lite is an "affordable," entry-level tablet designed to "work seamlessly" with the company's other hardware. Finally, the OnePlus Buds 4, available in "Zen Green" and "Storm Gray" color options, promise high-quality sound with dual drivers, Hi-Res audio support, and a low-latency mode for gaming. The launch event is set for July 8, where we will get the full specifications and, more importantly, the pricing for everything.
    • ok i have start11 installed on my desktop, how do i enable the start menu to look like win10. In otherwords, how can i right click on a file and next step would be to delete if i want to.   ty
  • Recent Achievements

    • Week One Done
      patrickft456 earned a badge
      Week One Done
    • One Month Later
      patrickft456 earned a badge
      One Month Later
    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      631
    2. 2
      ATLien_0
      282
    3. 3
      +FloatingFatMan
      175
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      128
  • Tell a friend

    Love Neowin? Tell a friend!