Utilizing CakePHP 3.0 with jQuery UI for an autocomplete feature

Seeking assistance on why the current code isn't functioning. The objective is to retrieve data from the index controller to search and obtain JSON data. No requests are being made, and there are no visible results.

New to CakePHP 3.0, I am attempting to implement an autocomplete/autosuggest feature. However, resources for CakePHP 1.3 are outdated or simply not compatible with CakePHP 3.0, leaving me unsure of what steps to take in order to achieve the desired functionality within CakePHP 3.0.

The specific requirement is for CakePHP 3.0 to enable autosuggestion as outlined in the following snippets:

<?php
namespace App\Controller;

use App\Controller\AppController;

class CarsController extends AppController {    

    public function index() {
        $this->loadComponent('RequestHandler'); 
        if ($this->request->is('ajax')) {
            $term = $this->request->query('term');
            $carNames = $this->Car->getCarNames($term);
            $this->set(compact('carNames'));
            $this->set('_serialize', 'carNames');
        }
    }
}
?>
<?php
namespace App\Model\Table;

use Cake\ORM\Table;

class Carstable extends AppModel {

    public function getCarNames ($term = null) {
        if(!empty($term)) {
            $cars = $this->find('list', array(
                'conditions' => array(
                    'name LIKE' => trim($term) . '%'
                )
            ));
            return $cars;
        }
        return false;
    }
}
?>

<?php
//loading jQuery libraries from Google CDN
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));

//file inclusion required for autocomplete field functionality

//form with autocomplete input field
echo $this->Form->create();
echo $this->Form->input('name', array('class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->end();
?>

<script type="text/javascript">
(function($) {
$('#autocomplete').autocomplete({
source: "<?php (array('controller'=>'Cars','action'=>'search')); ?>",
datatype:"json",
minLength: 1
})
})
</script>

Answer №1

To enable autocomplete functionality in CakePHP 3.0, follow these steps:

Create a new view for search at \Template\post\Search.ctp

<?php
use Cake\Routing\Router;
use Cake\View\Helper\UrlHelper;

?><div class="ui-widget">
<?php
        echo $this->Form->create('Posts', array('action' => 'search'));
        echo $this->Form->input('name',array('id' => 'Autocomplete')); 
       
        echo $this->Form->end();
    ?></div><div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script type="text/javascript">
      $(document).ready(function($){
    $('#Autocomplete').autocomplete({
  source:'<?php echo Router::url(array("controller" => "posts", "action" => "search")); ?>',
  minLength: 1
    });  });
</script>

Add the following function to your PostController.php file:

 public function search() 
       {
        if ($this->request->is('ajax')) {
            
            $this->autoRender = false;            
            $name = $this->request->query('term');            
            $results = $this->Posts->find('all', array(
                                           'conditions' => array('Posts.title LIKE ' => '%' . $name . '%')
                                         
                                           ));
            
            $resultArr = array();
            foreach($results as $result) {
               $resultArr[] = array('label' =>$result['title'] , 'value' => $result['title'] );
            }
            echo json_encode($resultArr);              
}}

Include the line below in your routes.php file:

Router::extensions('json', 'xml');

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

Sorting information in the React Native Section List

Working with React Native's SectionList and filtering data: data: [ { title: "Asia", data: ["Taj Mahal", "Great Wall of China", "Petra"] }, { title: "South America", data: ["Machu Picchu", "Christ the Redeemer", "C ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

phpMyAdmin and MySQL mistakenly flag a duplicity error on a UNIQUE column even when no actual duplicity exists

I have the following table structure: CREATE TABLE user_info ( user_index INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY, user_first_name VARCHAR(250) NOT NULL, user_last_name VARCHAR(250) NOT NULL, user_email VARCHAR(250) NOT NULL, user_t ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Uploading numerous images with sequential identification numbers

I have implemented the following code for uploading multiple images at once. My requirement is that when I upload multiple images in a single column, they should be labeled as 1, 2, 3, 4, 5. Then, if I upload more images later on, they should continue the ...

Tips for customizing babel's preset plugin configurations

I've integrated babel-preset-react-app into my project with the following .babelrc configuration: { "presets": ["react-app"], "plugins": [ "transform-es2015-modules-commonjs", "transform-async-generator-functions" ] } Currently, I&apos ...

Leverage the power of dynamic PHP variables within your JavaScript code

I have an image database and a search form. I want to display the images on the next page using JavaScript with the OpenLayers library. Here is the PHP code I wrote: <?php mysql_connect('localhost','root',""); mysql_select_ ...

What distinguishes defining a function through a prototype versus as a class property?

Check out this code snippet: Apple defines its function using a prototype. Banana defines its function using a class property. var Apple = function(){} Apple.prototype.say = function(){ console.debug('HelloWorld'); } var Banana = functio ...

The functionality of angular-ui's ui-utils and ui-scroll module is currently nonfunctional in version 0.1.0

I have been trying to implement the features from this Angular UI library: http://angular-ui.github.io/ui-utils/, particularly focusing on this aspect: https://github.com/angular-ui/ui-utils/blob/master/modules/scroll/README.md Unfortunately, despite my e ...

Error: The constructor for JsSHA is not valid for the TOTP generator

Attempting to create a TOTP generator similar to Google's timed-based authenticator using the React framework. I am utilizing the bellstrand module for TOTP generation, but I am encountering issues when trying to import it into my React code. Here is ...

Can I rely on fopen to execute a cURL operation with file upload securely?

I have implemented an upload system that utilizes Dropbox's API to send files. The receiving .php file that performs a cURL operation looks like this: $localFile = $_FILES["file_key"]['tmp_name']; $fp = fopen($localFile, 'r'); $c ...

Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its correspondi ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...

Even after applying trim() function, PHP's return statement still adds spaces unnecessarily

My function is supposed to return a boolean, but for some reason, it is adding spaces at the beginning of the string. Even after using trim(), the spaces persist. What could be causing this unexpected behavior? PHP function checkFile($v){ $result = is_ ...

What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting ...

Getting just the main nodes from Firebase using Angularfire

I'm having trouble figuring out how to print just the parent element names from the structure of my database. The image provided shows the layout, but I can't seem to isolate the parent elements successfully. ...

Incorporate the block-input feature from sanity.io into your next.js blog for enhanced functionality

Currently, I'm in the process of creating a blog using next.js with sanity.io platform. However, I am facing some difficulties when it comes to utilizing the code-input plugin. What's working: I have successfully implemented the code component b ...

The functionality of the input text field being draggable and resizable is not functioning properly

I have created a plunk where I implemented jQuery resizable and draggable on an input field of type text. However, I am facing two issues. Firstly, the draggable functionality is not working as expected. Secondly, the resizable feature only seems to work w ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...