Symfony2: Using Ajax to send data to a controller

I have implemented a search input on my website that allows users to search for content within my database. I want this search input to function similarly to the search bar on Facebook, using Ajax for instant searching. Despite trying various code snippets with the keyup event, I have not been successful in getting it to work.

Here is the routing configuration:

acme_estm_site_espace_supr_admin_recuperer_donnes_recherche:
    path: /chercher
    defaults: { _controller: AcmeEstmSiteBundle:Default:recupererdonnesrechercheAction}

And here is the relevant controller code:

$('#search').keyup(function(key) {
    var query = $(this).val();

    var data = {
        request: query
    };

    $.ajax({
        type: "POST",
        url: "{{ path('acme_estm_site_espace_supr_admin_recuperer_donnes_recherche') }}",
        data: data,
        success: function(response, dataType) {
            alert(response);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('Error : ' + errorThrown);
        }
    });
});

public function recupererdonnesrechercheAction(Request $request){
    if($this->getRequest()->isXmlHttpRequest()){
        echo "This is an Ajax request";

        $data = $request->request->get('request');
        echo $data;
    }

    return new Response();
}

When testing the functionality, I encountered an alert error stating "Error: Not Found."

If anyone could assist me in resolving this issue, I would greatly appreciate it. Thank you in advance.

Answer №1


Hey there,

After looking through your code, I noticed that you are using Request $request as a parameter and checking for XMLHttpRequest with

if($this->getRequest()->isXmlHttpRequest()){
. Finally, you are retrieving data with
$request->request->get('request');
.

I believe you should make some changes like below:

public function retrieveSearchData(){

     if($this->getRequest()->isXmlHttpRequest()){

         echo "This is an ajax request";

         $data = $this->getRequest()->request->get('request');
         echo $data;

     }

    return new Response();

}

Also, when defining the route, consider removing "Action" from your method name:

acme_estm_site_espace_supr_admin_retrieve_search_data:
    path: /search
    defaults: { _controller: AcmeEstmSiteBundle:Default:retrieveSearchData }

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

Unique many-to-many relationships in Symfony using Doctrine

I have two entities with a many-to-many relation that I have transformed into two one-to-many relations. To achieve this, I created another entity called CollanaCollezionista which has some attributes. I want to ensure that the combination of collana and ...

What is the purpose of <Component render={({ state }) => {} /> in React?

Currently delving into the world of ReactJS, I decided to implement fullPageJS. It seems to be functioning properly, although there are certain syntax elements that remain a mystery to me. Take a look at the component below: function home() { return ( ...

The image will remain hidden until it is fully loaded and ready to be displayed

I am currently working on a script that involves displaying a loading icon until an image is fully loaded, at which point the loading icon should disappear and the image should be shown. Unfortunately, my current code is not working as intended. Here is a ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

Creating a basic jQuery button to switch an element's background color is a breeze

I'm new to this, so I hope this is a straightforward question. I'd like to use the bgtoggle class as a button to switch the background color of the metro class. I know I'm doing something wrong because it's not working as expected. Any ...

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...

Creating a consolidated HTML table by extracting and comparing data from various JSON files

Being new to JS and JSON, I am struggling to find a suitable solution that works for me. I have two distinct json files. The first one: players.json contains the following data: { "players": [ { "id": 109191123, "surnam ...

The filter functionality isn't functioning properly when attempting to filter an array of objects within a Vuex action

I have a collection of objects that is accessed through a getter. I am using this getter inside an action to filter the items, but no matter what I do, the filtering does not seem to work and it ends up returning all the mapped item IDs. filterItems({ gett ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

How can I eliminate the default background of Mui tooltip and personalize it in react?

Below is an example of how to customize a nested tooltip within a default background tooltip in MUI. The challenge here is to remove the grey border in the customized tooltip and have only a white background with black text. Check out the code snippet be ...

Retrieve well-known individuals from the Wikipedia API

I am currently working on retrieving information about living individuals from the Wikipedia API, but I am struggling to find a way to achieve this. While browsing, I stumbled upon this question, which deals with the same issue as mine. From what I gather ...

The search bar fails to display all pertinent results when only a single letter is inputted

How can I create a search functionality that displays array object names based on the number of letters entered? When I input one letter, only one result shows up on the HTML page, even though the console.log displays several results. The desired output is ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

What would be more efficient for designing a webpage - static HTML or static DOM Javascript?

My burning question of the day is: which loads faster, a web page designed from static html like this: <html> <head> <title>Web page</title> </head> <body> <p>Hi community</p> </bo ...

Execute a JavaScript function repeatedly, with a specified delay incorporated into it

I am currently working on a JavaScript function that cycles through background images within a div. The function works well, but it stops once all the images have been displayed. How can I make it start over again after going through all the images? $(do ...

Removing an item from a React (Hooks) array state: A step-by-step guide

In my code, I have a list of text inputs populated from an array and I am trying to delete a specific element based on its index. The issue I am facing is that even though the console log correctly shows the updated array without the removed element, visua ...

Displaying the data from a database on a browser using node.js, MySQL, and Jade

Currently, I am delving into Node.js, Express.js, and Jade while utilizing a MySQL database. As a newcomer to node.js, I decided to start with something simple: presenting data from the database in a table on the browser. Unfortunately, my attempts have no ...

Developing a tool for switching between languages in an internationalization application

I have been exploring the implementation of Lingui(i18n) in apps. All set up, but I'm interested in adding a language switcher to enable users to change between language catalogs on my app. Here's my index.js file: import React, { useEffect } fr ...

Update a specific div using Ajax with auto-refresh functionality

I am attempting to implement an automatic refresh every 5 seconds on a div using AJAX intervals, but I seem to be missing something. Here is the code for my div: <script> function loadlink(){ $('#chart').load(function () { ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...