George Nicolaou George Nicolaou - 4 months ago 8
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

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

//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)) {
$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];
}

echo json_encode($rows);
}
getOptions();
?>


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

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];


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

$.get("http://localhost/test-app/get_app_settings.php",function(data){
var json = JSON.parse(data);
console.log(JSON.stringify(json));
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

What's your intention of doing this?

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

Maybe you want just this?

$rows[$r['option_name']]=$r['option_value'];