views:

39

answers:

2

I run a mysql query and get the results successfully. However, I cannot read the elements of the array from javascript side. Can anyone help??

//JAVASCRIPT makes a request

function profiles(){

$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "text");

}

function fillProfileCombo(res) {

alert(res);

}

//dbConn.php takes the request , gets the result and passes via echo as it is shown as follows:

//RETURN PROFILE LIST else if (!strcmp($opType, "getProfileList")){ //no param is coming

$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() ); mysql_select_db( $db_name ) or die( mysql_error() );

$profiles = mysql_query(" SELECT DISTINCT profileName FROM map_locations "); $row = mysql_fetch_array($profiles); /*while() { echo $row['FirstName'] . " " . $row['LastName']; echo "
"; } */ //$data = array(); //$row = mysql_fetch_assoc($profiles) /*while($row = mysql_fetch_assoc($profiles)) { $data[] = $row; }*/

if ($row){ echo $row; } else { echo "ERROR occured"; }

}

//PROBLEM:

//when I change echo $row; into echo $row[0]; , I see the first element in an alert box...query is definitely working..

//however when I change res to res[0], it does not show anything - which is normal because I do not know how to cast php array into js array..

function fillProfileCombo(res) {

alert(res[0]); // does not work..

} I do not want to use json by the way... I am not very good at. I do not want to mess it up. Any suggestion and help is appreciated.

Regards...

Ozlem.

A: 
// PHP
$res = array();
while ($row = mysql_fetch_array($profiles)) {
    $res[] = $row['profileName'];
}

header('Content-type: application/json');
echo json_encode($res);

// JavaScript
$.post('dbConn.php', { opType:"getProfileList" }, function(data) {
    alert(data.length + " profiles returned");
}, "json");
Phil Brown
Thanks Phil, I have corrected my code based on what you have sent me..
Ozlem
A: 

Thanks Phil..This works now.. I followed your way by changing sth.. Maybe it was working but I couldnt run it. Very similar except a couple of changes. I changed it as like this:

//PHP

        $data = array();
        while($row = mysql_fetch_assoc($profiles))
        {
            $data[] = $row;
        }

        if ($data){
            echo json_encode($data);

        } else {
            echo $data;
        }

//JS

    function profiles(){

        //$.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");
         $.post('dbConn.php', { opType:"getProfileList" }, fillProfileCombo, "json");

    }


    function fillProfileCombo(data) {
        alert(data[1].profileName);

    }
Ozlem
You should probably test the length of the JSON array before attempting to access specific indexes.
Phil Brown
yeah I did try what you said. I tried whatever you sent me as it is. But I could not run it. Anyway, I corrected it with your help. Many Thanks. Ozlem.
Ozlem