I must utilize the row variable obtained from my controller in order to transmit it to another controller using Ajax

When displaying a menu of categories and products for an authenticated user, I encountered a problem with the search bar. Despite wanting only certain categories/products to be displayed, the search bar was fetching products from all categories. To address this issue, I attempted to send a variable containing a list of category objects via an ajax request:

Illuminate\Database\Eloquent\Collection {#1381 ▼
  #items: array:1 [▼
   0 => App\Models\Categorie {#1385 ▶}
  ]
}

However, I faced an error with the $categories variable in my ajax script. I was unsure how to utilize this variable in my script to filter search results based on specific categories. Here is the script I attempted:

<script>
$(document).ready(function(){
    fetch_customer_data();
    function fetch_customer_data(query = '')
    {
        var data =[];

        $.each({{$categories}} , function( index, value ) {
            data.push(value->id);
        });
        console.log(data);
        $.ajax({
            url:"{{ route('search') }}",
            method:'GET',
            data: {query: query, data:data },
            dataType:'json',
            success: function(data) {
                if (data.success) {
                    $('#result').html(data.html);
                } else {
                    console.log(data.message);
                }
            }
        })
    }
    $(document).on('keyup', '#keyword', function($e){ // define event parameter
        var query = $(this).val();

        fetch_customer_data(query);
        $e.preventDefault();
    });
});

Here is the controller method:

    public function search(Request $request)
{
    try{
        if($request->ajax()) {
            $query = $request->get('query');
            if(empty($query)) {
                return back()->withError("Désolé, une erreur de serveur s'est produite (requête vide)");
             }
            else {
                $products =DB::table('product_categories')
                            ->join('produits', 'product_categories.produit', '=', 'produits.id')
                            ->join('categories', 'product_categories.categorie', '=', 'categories.id')
                            ->select('produits.*')
                            ->whereIn('product_categories.categorie',$request->data)
                            ->where([['nomProduit','LIKE','%'.$query.'%'],['categories.visibilite','=',1],['produits.visibilite','=',1]])
                            ->orWhere([['typeActivite','LIKE','%'.$query.'%'],['categories.visibilite','=',1],['produits.visibilite','=',1]])
                            ->get();

            }
            $total = $products->count();
            $html = view('front.search_result', [
                    'products' => $products,
                ])->render();


            return response()->json([
                'success' => true,
                'html' => $html,
                'total' => $total,
            ], 200);
        } else {
            return response()->json([
                'success' => false,
                'message' => "Oups! quelque chose s'est mal passé !",
            ], 403);
        }
    }catch (Exception $e) {
        Alert::error('Erreur ', $e->getMessage())->autoClose(false);
        return redirect()->back();
    }catch (Error $e) {
        Alert::error('Erreur ', $e->getMessage())->autoClose(false);
        return redirect()->back();
    }
}

Here is the structure of the variable $categories:

Illuminate\Database\Eloquent\Collection {#1381 ▼
    #items: array:1 [▼
      0 => App\Models\Categorie {#1385 ▼
    #fillable: array:4 [▶]
    #files: array:1 [▶]
    #connection: "mysql"
    #table: "categories"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:9 [▼
        "id" => 4
        "parent_id" => null
        "categorie" => "Informatique"
        "description" => "informatique"
        "photo" => "categories/Informatique .jpg"
        "visibilite" => 1
        "deleted_at" => null
        "created_at" => "2021-04-19 06:33:16"
        "updated_at" => "2021-08-07 14:06:45"
      ]
  #original: array:9 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

Finally, here is the error I encountered: https://i.sstatic.net/if52h.png

Answer №1

It appears that you should consider utilizing {! json_encode($categories) !}

Answer №2

Understood! Here's how I made it work:

<script>
$(document).ready(function(){
    fetch_customer_data();
    function fetch_customer_data(query = '')
    {
        var data =[];
        var cats = @json($categories->toArray());
        console.log(cats);
        $.each(cats , function( index, value ) {
            data.push(cats[index].id);
        });
        console.log(data);

        $.ajax({
            url:"{{ route('search') }}",
            method:'GET',
            data: {query: query, data : data},
            dataType:'json',
            success: function(data) {
                if (data.success) {
                    $('#result').html(data.html);
                } else {
                    console.log(data.message);
                }
            }
        })
    }
    $(document).on('keyup', '#keyword', function($e){ // define event parameter
        var query = $(this).val();

        fetch_customer_data(query);
        //$('#result').html(data.html); remove this line
        $e.preventDefault();
    });
});

Also, I made no changes in my controller, I simply passed the $categories using compact

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

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Troubleshooting the issue of JavaScript not executing on elements with a specific CSS class

I am attempting to execute a JavaScript function on each element of an ASP.NET page that is assigned a specific CSS Class. Despite my limited knowledge of JavaScript, I am unable to determine why the code is not functioning properly. The CSS Class is being ...

Ensure that the input field only accepts numerical values

Can anyone help me with an issue I'm facing in my plunker? I have an input text field that I want to accept only numbers. Despite trying normal AngularJS form validation, the event is not firing up. Has anyone encountered a similar problem or can prov ...

The Npm generate script is failing to create the necessary routes

I've integrated vue-router into my nuxt project, but I encountered an issue when running npm run generate - it generates everything except for my pages. I suspect the problem lies with the router implementation as I didn't face any issues before ...

Modifying the .textcontent attribute to showcase an image using JavaScript

I am working on a website and I want to change editButton.textContent = 'Edit'; so that it displays an image instead of text. var editButton = document.createElement('button'); editButton.textContent = 'Edit'; After exploring ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

Unusual outcomes stemming from JavaScript nested for loops

In my current project, I am working on verifying a submitted string against a set of letters. If the word_string is "GAR", the expected output should be "GAR" because all these letters are found in the letter set. However, I am facing an issue where some ...

"Troubleshooting: IE compatibility issue with jQuery's .each and .children functions

I have created an Instagram image slider feed that works well in Chrome, Safari, Firefox, and Opera. However, it fails to function in all versions of Internet Explorer without showing any error messages. To accurately determine the height of images for th ...

Using AOS in WordPress causes the specified elements to appear as blank rather than fading in

Struggling to integrate Michalsnik's Animate On Scroll plugin into my Wordpress site. Followed the instructions to add the "data-aos" attribute to a div, but the element ends up being blank instead of fading in. <div class="textbox center branch-b ...

Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a ch ...

Is there a way to organize data by month using Chart Js?

I have been working with Chart.js and encountered an issue while trying to organize the dates fetched from my MongoDB to display them according to the respective month. In the provided image, the line does not seem to align with the correct month index. I ...

Tips for sending a PHP variable to a jQuery tooltip with the help of Ajax

I'm facing an issue with the event_id PHP variable in the current page. I need to display it in a jQuery tooltip using AJAX, but I keep getting an error that the event_id is not defined. Here's the jQuery file with the tooltip function: functio ...

Guide to sending ajax content to a controller in codeigniter

Having trouble posting data to the controller in CodeIgniter for autocomplete functionality with a database. Struggling to send typed or selected data from the view to the controller using AJAX. Below is the AJAX function: var i=$('table tr').le ...

Utilizing jQuery's nextUntil() method to target elements that are not paragraphs

In order to style all paragraphs that directly follow an h2.first element in orange using the nextUntil() method, I need to find a way to target any other HTML tag except for p. <h2 class="first">Lorem ipsum</h2> <p>Lorem ipsum</p> ...

Netlify is failing to recognize redirect attempts for a Next.js application

After successfully converting a react site to utilize next.js for improved SEO, the only hiccup I encountered was with rendering index.js. To work around this, I relocated all the code from index to url.com/home and set up a redirect from url.com to url.co ...

A function designed to retrieve all nearby values within a list

After spending quite some time trying to tackle the problem at hand, I find myself stuck. I am dealing with a list of various values, such as: list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905) I am looking to create a function that can identify a ...

Generating a fresh array of unique objects by referencing an original object without any duplicates

I can't seem to figure out how to achieve what I want, even though it doesn't seem too complicated. I have an array of objects: { "year": 2016, "some stuff": "bla0", "other stuff": 20 }, "year": 2017, "some stuff": "bla1", ...

Is there a way to create a Vue.js component that retains the data I have added to it even when transitioning between routes? Currently, whenever I switch routes, the component deletes all the previously

I'm currently working on a webshop using Vue.js. When I add products, I utilize an event bus to pass the data to the CartComponent. Everything works as expected; however, if I navigate back or reload the page, all the data in my CartComponent gets del ...

Guide on invoking setImmediate prior to or above .on('data') in fast-csv using Node.js

I'm currently utilizing fast-csv (https://www.npmjs.com/package/fast-csv) for parsing a csv file. The file could possibly contain 10k records, leading to significant delays in parsing and blocking other operations on the server. To address this issu ...