The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Hybrid View

Getting data from PHP into JavaScript

I need to transfer up to some 15 items of data from PHP into JavaScript. I've normally done this by creating hidden inputs with PHP and then using 'getElementById' to extract the value. But it's getting a bit cumbersome, with loops to create the inputs, and more loops to extract. It works, but I wonder if there's a better way ?

I have the information available as a GET string. There are (three) sub-arrays in the GET, and the number of values which may be present in each sub-array varies from 0-9. The GET array keys are strings, but the sub-array keys are numeric.

The GET is derived from check-boxes on a search filter form, and the purpose of all this is to transfer the checks from one page to the next (which has the the search results) so that the filter form can be re-presented.

If you just want to have a way to supply javascript with some data, take a look at php's json_encode() function. Then you have an object/array structure to use.

But, it sounds like you shouldn't be using javascript for this. Why don't you have php just generate the appropriate html? It's a very common thing to prepopulate values for form fields, including state flags like checked and selected etc...

I believed I needed to use JavaScript because the values I'm bringing forward are those entered by the visitor. The search form is currently 'pure' HTML. I expect I could rewrite it with PHP to set 'checked' as per the GET string, I just hadn't thought of it. I guess I should have done, but sometimes one gets a bit blinkered.

Thank you. Yes, I recognise this, but there are plenty of other things that don't work without JS (like being able to roll up the search filter forms). It's a matter of where you draw the line.

However, as this can be done with PHP, that's what will have to happen.
A prototype may be seen at http://www.holidaymullandiona.com/index.php Should you go there, please note that only the accommodation search has been implemented.

Well, it wasn't nearly as difficult as I thought it would be to do it all in PHP. Thank you for prodding me in that direction. (The prototype site is still working with JS, but will get fixed in the next couple of days).