George Nicolaou George Nicolaou - 1 year ago 56
Javascript Question

Get correctly formatted json from php to javascript?

I have a database with a tabled named options. In this table I have 3 fields

  1. id of type int autoincrement

  2. option_name of type varchar

  3. option_value of type varchar

Assume I have the following to records inserted already

  1. '1','homepage_title','Home'

  2. '2','index_page_title','Index Page'

I have a php script as follows

header("Access-Control-Allow-Origin: *");
//set timezone becuase some servers are jsut wrong
define('TIMEZONE', 'Europe/Athens');

//Connect & Select Database
mysql_connect("somehost","simeuser","somepass") or die("could not connect server");
mysql_select_db("somedbdb") or die("could not connect database");

function getOptions(){
$sqldata = mysql_query("SELECT * FROM `options`");
$rows = array();
while($r = mysql_fetch_array($sqldata)) {

echo json_encode($rows);

It works because the script returns something like this

{"homepage_title":{"Home":["Home"]},"index_page_title":{"index page":["index page"]}}

I am sure the line that is incorrect is this one


I just can't figure out what I need to fix. My intensions is to call javascript as follows

var json = JSON.parse(data);
alert("homepage title was "+json['homepage_title']);
alert("index page title was "+json['index_page_title']);

I get Object object instead of Homepage which I expected in homepage_title and Index page which I expect in index_page_title.

I am sure it something really stupid but I just can see it.

Answer Source

What's your intention of doing this?


Maybe you want just this?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download