Angular so that the autocomplete field is filled with information retrieved from a PHP URL

I am currently utilizing an autocomplete field that needs to fetch data from a MySQL database based on a PHP (YII2) action. The autocomplete field is currently being populated statically. Below is the code used to populate the autocomplete field:

app.controller('DemoCtrl', DemoCtrl);

function DemoCtrl($timeout, $q) {
    var self = this;

    // list of `state` value/display objects
    self.states = loadAll();
    self.selectedItem = null;
    self.searchText = null;
    self.querySearch = querySearch;

    // ******************************
    // Internal methods
    // ******************************

    /**
     * Search for states... use $timeout to simulate
     * remote dataservice call.
     */
    function querySearch(query) {
        var results = query ? self.states.filter(createFilterFor(query)) : self.states;
        var deferred = $q.defer();
        $timeout(function () {
            deferred.resolve(results);
        }, Math.random() * 1000, false);
        return deferred.promise;
    }

    /**
     * Build `states` list of key/value pairs
     */
    function loadAll() {
        var allStates = 'Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware,\
              Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana,\
              Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana,\
              Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina,\
              North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina,\
              South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia,\
              Wisconsin, Wyoming';

        return allStates.split(/, +/g).map(function (state) {
            return {
                value: state.toLowerCase(),
                display: state
            };
        });
    }

    /**
     * Create filter function for a query string
     */
    function createFilterFor(query) {
        var lowercaseQuery = angular.lowercase(query);

        return function filterFn(state) {
            return (state.value.indexOf(lowercaseQuery) === 0);
        };

    }
}

In the function loadall(), I need to fetch values from my database, which are returned from my YII2 controller action. It can be accessed via URL. My controller action is as follows:

public function actionGetAllPackages()
{
    $packages = \common\models\Packages::find()
            ->select('name')
            ->all();
    $name = "";
    foreach ($packages as $package)
    {
        $name = $name.', '.$package->name;
  }
     $name = substr($name, 2);
    echo addslashes($name);
}

How can I retrieve the value printed in the controller action within the Angular function? Please help. This is my first time using YII2 and Angular.

Thanks in advance

Answer №1

To retrieve all packages, simply use a `$http` request to your GetAllPackages() function located in the controller. Within the script's loadAll() method, capture the result and store it in the variable allstates.

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

How to Use Jquery to Retrieve the Selected Option Value and Append a Parameter

I am attempting to expand the value by adding "&fullpage=true" <select name="navMenu" onchange="go(this.options[this.selectedIndex].value)"> <option value="-">Choose</option> <option value="page.html&amp;nyo=0" class="ccbnLnk" ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

How can I prevent the substitution of "&" with ""&amp;" when using PHP's include function?

$mRef = $payment[ID]; $sign = $mCode.$mRef.$secureKey; $sign = hash('sha256', $sign); $link = ("https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?merchantCode=".($mCode)."&merchantRefNumber=".($mRef)."&si ...

Having trouble with submitting the jQuery form

I have written a script to submit a form after validation and receive the values in a PHP file using $_POST. However, I am not able to retrieve the values in the PHP file. When I try to echo the values, it shows up as blank. Can someone please guide me a ...

Require modifying the radio button's value based on the presence of a certain class in an input field

Feeling overwhelmed. I am currently working on implementing a credit card auto system using the Stripe Payment plugin, but I find myself at a loss. Specifically, when a MasterCard is entered in the card number input field, it should receive the "masterca ...

Is Dart the new AngularJS in terms of programming style?

Is there a software library or project available that allows for programming in Dart using an AngularJS style approach? I am interested in creating annotated HTML files to declare my UI rather than instantiating everything imperatively like with SWT. I wo ...

Decrypting using openssl_private_decrypt will face issues due to the presence of apostrophes in the text

I securely store sensitive information in a MySQL database using the 'text' field format, encrypting it with openssl_public_encrypt and decrypting it with openssl_private_decrypt. However, I am encountering an issue when attempting to decode the ...

Trigger Click event when clicking on navigation link using the ID

Currently, I am working with a WordPress theme that includes a page with 10 tabs that open individually. My approach so far has been to provide links to all tabs in the navigation bar. For instance, href="mylink.com/#tabid" It works perfectly when the p ...

Using Laravel for login with the option to choose from multiple usernames

I am looking to enhance my Laravel VueJS application by allowing users to log in using their username and registration number instead of just an email. I have successfully implemented this functionality by modifying the username function within the Authent ...

Here is a unique rewrite: "Strategies for effectively passing the data variable in the geturldata function within Vue.js on the HTML side vary

How can I properly pass a variable in the getdataurl function in Vue.js? I need help with passing a variable in getdataurl function in Vue.js. Please provide a clear explanation and include as much detail as possible. I have tried doing some background r ...

Exporting SQL query data as a JSON object in PHP is proven tricky due to the inability to populate an array with the

I am a beginner in PHP and I'm trying to use the following function to fetch data from MySQL and populate an array, but I keep getting null values. function FetchBusinessData($connection, $email) { $query = "SELECT * from Business WHERE B_E ...

What is the integration of Google URL format with a PHP application?

When it comes to php websites, URLs are commonly written in the form of page.php?id=123 or rewrite moded page/Id/123 However, when looking at google I observed that URLs look more like google.com/search?q=Wordpress I attempted to structure website links ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Generating a PHP JSON array on the fly with dynamic content

I have generated a JSON using PHP code like this. $result=mysqli_query($mysqli,"SELECT * FROM service_provide WHERE personal_id='".$personal_id."'") or die(mysqli_error($mysqli); $row = mysqli_fetch_assoc($result); while($row = mysqli_fetc ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

Error: Invalid argument encountered in CakePHP i18n translation formatter U_ILLEGAL_ARGUMENT_ERROR

When I was working with Cakephp 2, I relied on this specific repository for cake.po translations. Unfortunately, it appears that this repository has not been updated for use with Cakephp 3. As a result, I followed the instructions provided here and execute ...

terminate() displaying a message and return with a non-zero exit code

There are two files I am working with: #!/usr/bin/php <?php exit("Unable"); //1st option #exit(1); //2nd option #exit(); //or exit(0) //3rd option ?> The second file is named second.php: #!/usr/bin/php <?php exec("./first.php",$out,$err); ...

Data not populating correctly in MEAN Stack application

Currently grappling with the challenge of making this web app operational using the MEAN Stack, I find myself at a standstill. The root cause is unclear to me. Upon refreshing my page and commencing data entry by filling out all fields before clicking on " ...