user2056238
user2056238

Reputation: 83

Passing array in HTML form with Jquery

I'm trying to use Jquery to pass an array to an HTML form as follows:

$('form#'+ID1+' input#myArray').val(theArray);

Then my form is as follows

<input type="hidden" id="myArray" name="myArray"> 

I then serialize before calling an Ajax request:

var dataString=$('form#grid1').serialize();

But on the receiving script I get:

Uninitialized string offset: 1

Any ideas?

Thanks!

Upvotes: 0

Views: 2818

Answers (1)

John S
John S

Reputation: 21482

Here's my best guess from what you are showing in the question.

When you call the following, the array represented by theArray is converted into a comma-separated string and placed in the hidden input element. This is the case even if theArray is a nested array.

$('form#'+ID1+' input#myArray').val(theArray);

But on the server, you are trying to treat the posted "myArray" value as an array, so you get the following error:

Uninitialized string offset: 1

The problem is that "myArray" is not an array, but is a comma-separated string.

I recommend formatting the theArray value as JSON before setting it into the hidden input element, especially if it is a nested array. You can do this:

$('form#'+ID1+' input#myArray').val(JSON.stringify(theArray));

Then parse it to an object on the server side. I'm guessing from the error message that you are using PHP, so you would do something like this:

$myArray = json_decode($_POST['myArray']);

Upvotes: 1

Related Questions