Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a javascript array to a form / $_POST without ajax

I'm working on a form upload element that can be used in the Zend Framework forms. I'm trying to make it so the programmer can use it in any project without having to manually configuring any settings.

The files are uploaded by an AJAX uploader which returns JSON data like:

[
  {
      "name":"image.png",
      "size":42410,
      "type":"image\/png",
      "url":"http:\/\/example.com\/image.png",
      "thumbnail_url":"http:\/\/example.com\/thumbnail\/image.png",
   }
]

Since the uploader itself is a form element I'm trying to put that data in the form so on the submit the values can be retrieved from the $_POST. I was adding hidden input fields with javascript named uploader-data[] (when submitting the form) but that only allows me to pass 1 variable at the time to the hidden field.

So I guess my question is: "How can I pass the whole array/object to the $_POST / form?". Even though I am using AJAX for the uploader itself I don't want to use it to submit the form. I want a regular form submit containing all the data from the JSON object/array. The files itself are already uploaded but I might want to use the JSON data in my database or at some other place.

Is it possible to do something like this?

Thanks in advance.

like image 558
Ilians Avatar asked Dec 08 '11 14:12

Ilians


1 Answers

Put your javascript value into an input field using JSON.stringify :

data = [
  {
      "name":"image.png",
      "size":42410,
      "type":"image\/png",
      "url":"http:\/\/example.com\/image.png",
      "thumbnail_url":"http:\/\/example.com\/thumbnail\/image.png",
   }
]
document.getElementById('my_hidden_input').value = JSON.stringify(data);

This will turn your array in the following text value:

[{"name":"image.png","size":42410,"type":"image/png","url":"http://example.com/image.png","thumbnail_url":"http://example.com/thumbnail/image.png"}]

Zend can parse the JSON value into a php array.

like image 141
jantimon Avatar answered Sep 20 '22 16:09

jantimon