Reputation: 5933
Problem:
I have an array in JS that looks like this:
["intelligence", "skin", "weight", "volume"]
This is stored in a var called "newListASource". I apply this var to a form and then submit it using POST.
// Form destination
var formUrl = 'explorer.php',
// Generate the form
$form = $("<form action='"+ formUrl +"' method='post'></form>")
.append("<input type='hidden' name='Perspective' value='" + newListASource + "'>")
.append("<input type='hidden' name='form_submitted' value='true'>")
.appendTo('body');
// Submit the form
$form.submit();
When I pick it up through PHP and print it out, it gives me a string with commas. For instance:
skin,weight,intelligence,volume
Desired output I would like is (with trimmed spaces in the beginning and end):
skin weight intelligence volume
Upvotes: 3
Views: 6876
Reputation: 11832
What you can also do is just send the array as an array!
var formUrl = 'explorer.php';
var $form = $("<form action='"+ formUrl +"' method='post'></form>")
.append("<input type='hidden' name='form_submitted' value='true'>")
.appendTo('body');
while(newListASource.length)
$form.append($("<input type='hidden' name='Perspective[]' value=''>").val(newListASource.shift()));
$form.submit();
Php will then actually have an array inside $_POST['Perspective']
.
(Beware the input name is now Perspective[ ] to indicate it will be an array.)
Upvotes: 0
Reputation: 29166
newListASource.join(' ')
will give you the desired result -
// Generate the form
$form = $("<form action='"+ formUrl +"' method='post'></form>")
.append("<input type='hidden' name='Perspective' value='"
+ newListASource.join(' ') + "'>")
.append("<input type='hidden' name='form_submitted' value='true'>")
.appendTo('body');
// Submit the form
$form.submit();
See the doc.
Currently you are getting comma separated values because newListASource.toString()
is called whenever you are concatenating your array with a string, and this is the default behavior of toString
method for arrays. When you call join
, however, it converts your array to a string, separated by the delimiter that you pass to it as argument. So you get values separated by spaces in this case.
Upvotes: 5
Reputation: 74738
You can use .join()
and $.trim()
:
// Form destination
var formUrl = 'explorer.php',
newListASource = newListASource.join(' ');
then in the form you can change to this:
$.trim(newListASource)
Upvotes: 2
Reputation: 2334
var arr = ["intelligence", "skin", "weight", "volume"];
var result = ary.join(',');
Upvotes: 0
Reputation: 388316
Since you are using an array use Array.join() with the separator as ' '
"<input type='hidden' name='Perspective' value='" + newListASource.join(' ') + "'>"
Upvotes: 5