The Decks of Bicycle
The Decks of Bicycle

Reputation: 83

Converting a php object to javascript array

I have a selectAll function which returns the results as objects.

$customers = $app['database']->selectAll('customers');

Here is the var_dump for $customers variable just in case:

array(4) { 
    [0]=> object(stdClass)#5 (7) { ["id"]=> string(2) "10" ["name"]=> string(10) "Thisted El" ["address"]=> string(13) "Otto Monsteds" ["city"]=> string(5) "Vej 8" ["phone"]=> string(9) "503982350" ["zip"]=> string(6) "481922" ["notes"]=> string(0) "" } 
    [1]=> object(stdClass)#6 (7) { ["id"]=> string(2) "11" ["name"]=> string(11) "Bibin Vinod" ["address"]=> string(8) "Kottayam" ["city"]=> string(5) "Kochi" ["phone"]=> string(10) "0294294022" ["zip"]=> string(6) "129042" ["notes"]=> string(0) "" }
} 

I need to use the 'name' property of these objects for an auto-fill form. I am using the autocomplete script in this link.

In my php file, I have added the above autofill function after the form. Then I use json_encode on this object followed by JSON.parse. I use a loop to add just the names to a javascript array, and finally I pass it to the autocomplete function.

var js_data = '<?php echo json_encode($customers); ?>';

var js_obj = JSON.parse(js_data);

for (var i = 0; i < arrayLength; i++) 
{
   customername[i] = js_obj["name"];
}

autocomplete(document.getElementById("customers"), customername);

However the autofill form is not working. I'd like help regarding this issue. Thanks.

Upvotes: 1

Views: 2659

Answers (3)

The Decks of Bicycle
The Decks of Bicycle

Reputation: 83

I have fixed the problem. First I converted the object array to a normal array in PHP:

$customers = $app['database']->selectAll('customers');

$allCustomers = array();

foreach($customers as $key => $val) 
{
    $allCustomers[] = $val;
}

Then in the javascript part, I used json encode on this variable, and used a for loop to add each 'name' property to a javascript array, and finally passed it to the autocomplete function likewise:

var js_data = <?php echo json_encode($allCustomers) ?>;

var customername = [];

for (var i = 0; i < js_data.length; i++) 
{
    customername[i] = js_data[i]["name"];
}

autocomplete(document.getElementById("customers"), customername);

Thanks a lot everyone for offering your help.

Upvotes: 1

Barmar
Barmar

Reputation: 781058

js_obj is an array, you need to index it.

customername[i] = js_obj[i].name;

You could also just create an array of names in PHP.

$customers = array_map(function($x) {
    return $x->name;
}, $app['database']->selectAll('customers'));

?>
var customers = <?php echo json_encode($customers; ?>;

Upvotes: 0

andrea06590
andrea06590

Reputation: 1299

Because you simply need to change the input value instead of the div DOM

document.getElementById("customers").value = customername;

Upvotes: 0

Related Questions