Transforming a php object into a javascript array

I have a function called selectAll that returns results as objects.

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

Below is the var_dump of the $customers variable:

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 want to extract the 'name' property from these objects for an autofill form. I am using an autocomplete script found here.

In my PHP file, I have included the autofill function after the form. I encode this object using json_encode and then parse it using JSON.parse. By iterating over the array, I populate a JavaScript array with just the names and then 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);

Despite following these steps, the autofill form does not work as expected. Any assistance on this matter would be greatly appreciated. Thank you.

Answer №1

The issue has been resolved successfully. Initially, I transformed the object array into a standard array in PHP:

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

$allCustomers = array();

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

Subsequently, in the JavaScript section, I utilized json encode on this variable, employed a for loop to extract each 'name' property and populated them into a JavaScript array. Eventually, I passed it to the autocomplete function in this manner:

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);

I greatly appreciate everyone who contributed their assistance.

Answer №2

To update the customer name, just modify the input value without altering the div structure

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

Answer №3

To access the data in the `js_obj` array, you must use indexing.

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

If preferred, you can alternatively 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); ?>;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cross-platform mobile browsers typically have scrollbars in their scrollable divs

I have successfully implemented scrollable div's on a page designed for tablets running Android 3.2+, BlackBerry Playbook, and iOS5+ (except iPad 1). However, I would like to add scrollbars to improve the user experience. For iOS5, I can use the suppo ...

I am facing difficulties with deploying my Next.js App on Vercel. Whenever I try to deploy, I encounter an error stating that the Command "npm run build" exited with 1

Hey there! I'm currently following a tutorial by JavaScript Mastery on Next.js (big shoutout to you, sir). I've been trying to deploy it on Vercel, but running into some deployment issues and having trouble testing out different tutorials. Here&a ...

Issue with localStorage failing to save comments added at the beginning

Here is a link to the fiddle I am working on. My goal is to store prepended comments in a ul by saving the ul as a variable, and use localStorage to save it in the browser. The HTML structure of the project: <h1>Commentia!!!</h1> <textarea ...

Using the $.ajax() method can sometimes lead to encountering the error message "Uncaught ReferenceError: data is not defined"

I experimented with different methods to retrieve .json files and data using $.getJSON and $.ajax() here The issue I encountered with my JS code number 2 is: $.ajax({ type: "GET", url: 'js/main.js', data: data, success: 1, }).done(fun ...

Tips for automatically checking a form's accuracy before moving to the next stage in a multi-step form with zod and react-hook-form

In my application, there is a multi-step form. Currently, if a user skips some steps and tries to submit the form, it won't go through because they missed non-optional fields. The error messages appear at the previous steps, leaving the user unaware t ...

Error: Unable to locate module 'firebase'

import firebase from "firebase"; const firebaseConfig = { apiKey: "AIzaSyCcPSKlYtpdzBoAC8soeSmIARMzVKzrf5I", storageBucket: "challenge-4b2b2.appspot.com", messagingSenderId: "962418448875", ...

Add 1 to every element within an array with values ranging from 1 to 1000

As a newcomer to shell scripting, I am trying to increment the values of an array by one for each iteration. Here is my code: cmd=(1 2 3 4 5 6 7 8 ................) // How can I automatically pass numbers 1 to 1000 without typing manually. ${cmd[@]} for ...

Failure to trigger success or error callbacks in Angular's $http.get request

Trying to access the nutritionix v1_1 API through a get request has been a bit tricky. Despite the function being called successfully and passing the correct data, the $http.get request seems to be causing some trouble. It simply skips over the remaining c ...

Jackson serializes BasicFileAttributes

I need help serializing a class that contains the BasicFileAttributes interface. My approach involves using jackson for the serialization and deserialization processes. @JsonDeserialize(as = BasicFileAttributes.class) private final BasicFileAttributes ...

Creating a Spiral Matrix using a 2D Array in the C Programming Language

I am working on a C program to create a spiral matrix in a 2D array. I have successfully coded the matrix output, but I am facing issues with generating the spiral matrix. I am unable to identify the fault in my program. Any assistance would be greatly app ...

Adjusting the transparency level of the JavaScript thumbnail

I have implemented a plugin to showcase an image carousel on my website. The navigation thumbnails in the carousel are currently set to appear "greyed out" when not selected. Is there a way to adjust the level of grey for these thumbnails? Check out the l ...

Error: The code has a syntax issue due to an unexpected "function" token while using

Recently, I decided to try out Node version 6.2.1 with some of my code. My goal was to migrate the hyper-callback oriented codes to a cleaner and potentially more efficient approach. Surprisingly, when I attempted to run the node code in the terminal, an ...

What is the best way to transfer data from a clicked table row to another component?

I am currently working on developing an email inbox component for a system where the emails are displayed in a table format. When a user clicks on a specific row, it should lead to another component for further details. Since the information is not rende ...

Begin by opening a single div for each instance

I want a functionality where opening one div closes all the others. I've searched around for solutions and only found jQuery options, not pure JavaScript ones. Here is my code: function openDescription(description_id) { var x = document.getEle ...

Is it possible to incorporate click methods within vuex?

Recently, I've been delving into learning Vue and Vuex. One thing I noticed is that I have repetitive code in different components. To streamline this, I decided to utilize Vuex to store my data in index.js, which has proven to be quite beneficial. No ...

When transitioning from one screen to another in React Native, the toast does not appear. Setting a setTimeout of 1000 fixes this issue temporarily, but I am looking for a way to display

visitSite("openshift") setTimeout(() => { displayMessage('Shift Assigned', 'success'); }, 1000); // HOWEVER, I prefer to have the functionality of displaying a success message and navigating between screens separated into distin ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

What is the best way to implement function overloading in a React Functional Component using TypeScript?

I have experience writing React Functional Components and working with TypeScript for function overloading. However, when I try to combine the two, I find myself confused! Below is a snippet of code that showcases what I am trying to achieve: import Reac ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

Issue with distinguishing JavaScript code from an SVG file

Seeking assistance as I have an SVG file that is mostly composed of a script. My goal is to separate the script for compression purposes, but I am struggling to find a way to achieve this. Any guidance or help on this matter would be greatly appreciated. ...