Topic: Send a special(php array) data to javascript

Hi.

   I would like to send some data as "php (array key=>value)" to the javascript.
   I want use javascript to feed some html tag, as DIV, with the values. I can't use ID on the divs because maybe I will have more than one DIV with the same value, both divs will have the same html CLASS, so I can with javascript do something like:

if(div.CLASS==key) div.innerHTML = value;

   I thought about create a formated string as "$key=>$value;$key2=>$value2;" and request ->script('functionaname($data)');
   On javascript I can data.split(';') and split again "=>"
   But I'm not sure if there is a limit size for parameters on Javascript, but I can also send the data to a not_display_div and call the function to read the innerHTML of this div and split and feed the others divs.

   I'm looking for something more good well coding!
   Ideas?

Best Regards,
Guilherme

Re: Send a special(php array) data to javascript

Try this:
Use PHP's json_encode on the array and pass the resulting string to the js function using the response script function. Then use the JS json functions to process the info on the browser.


Ed

If you ever stop learning you may as well dig a hole, crawl in and pull the top over yourself.

Re: Send a special(php array) data to javascript

Hi Ed,

   Thanks that is totally useful!

   I got a problem that my database(mysql) uses latin1_spanish_ci char coding. I tried to convert to UTF8 on mysql CONVERT(FIELD AS using utf8) but the json_encode didn't accept. So I had to list the field on PHP and do a utf8_encode.
   Do you know why the UTF8 conversion from mysql couldn't get right?

Best Regards,
Guilherme Filho

Re: Send a special(php array) data to javascript

Glad to help.

Well I'm afraid I can't answer your question. I have never had to deal with such a problem. Could it be that there are special characters in the latin1_spanish_ci set that won't convert directly to utf8?

Ed

If you ever stop learning you may as well dig a hole, crawl in and pull the top over yourself.

Re: Send a special(php array) data to javascript

Hi,
  I don't think so, because when I use utf8_encode it works simply fine. I just don't want to wast processing time to every time convert each field using utf8_encode... I will try to create a view to see what happens.

   I let you know!
   Thanks again!
Guilherme Filho

6 (edited by gui_calabria 2014-07-24 1:39:30 PM)

Re: Send a special(php array) data to javascript

Hey Ed,
   
   The solution I got is easier then do CAST or CONVERT. I just had to add:

$mysqi->set_charset("utf8");

   Before request the data... now is working fine with json.
 
   My data is still be saved on latin1.

 
Best Regards,
Guilherme

Re: Send a special(php array) data to javascript

Great solution! I have never used that mysqli function. Learn something new every day.

Ed

If you ever stop learning you may as well dig a hole, crawl in and pull the top over yourself.