Issue encountered in transferring Json data from controller to view, Laravel version 5.6

I'm struggling to convert the Json value received from my controller into a properly readable JavaScript value.

This is my controller:

    $room = Room::
        select('id', 'name', 'capacity', 'status')
        ->get();

    $this->rooms = json_encode($room);;

    return view('admin.rooms.index', $this->data);

When I use {!!$room!!} in the view, I get:

[ {"id":1,"name":"room1","capacity":4,"status":"dirty"},{"id":2,"name":"room2","capacity":5,"status":"clean"},{"id":3,"name":"room3","capacity":5,"status":"clean"} ]

So, I have the Json value I need.

However, when I use {!!$room!!} in my script:

               function loadResources() {
                    $.post( "{!!$rooms!!}",
                    { capacity: $("#filter").val() },
                    function(data) {
                        dp.resources = data;
                        dp.update();
                    });
                }

I encounter an error: Uncaught SyntaxError: missing ) after argument list.

That's the error message I receive.

If I create a file and put the Json value in it:

               function loadResources() {
                    $.post( "room.json",
                    { capacity: $("#filter").val() },
                    function(data) {
                        dp.resources = data;
                        dp.update();
                    });
                }

Everything works fine in this case.

I tried using JSON.parse() to make the value JavaScript-readable, but it didn't work.

How can I effectively use that Json value in my JavaScript code?

Answer №1

Avoid using json_encode on the result set.

Instead, pass the entire object to the view in the following way:

$room = Room::
        select('id', 'name', 'capacity', 'status')
        ->get();

return view('admin.rooms.index', $room);

When accessing the passed data in the view, you can retrieve values like this:

{{$room->id}}

Answer №2

Experiment with encoding the rooms data within the view using JavaScript. Afterwards, ensure to pass it to the loadResources function.

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

Regular Expression in JavaScript: Find all matches except those within [[ ]] brackets

My <textarea> contains a list of names with spaces between them, so I created a function to replace the spaces with new lines. However, I now need to ensure that two or more spaces between names are considered part of the same element. For example: ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

Tips for accessing the assigned variable within and outside of a function

Currently, I am working with Webdriverjs and facing an issue. I am trying to assign a variable in a function and then compare that result with some data retrieved from a csv file. However, I am encountering a problem where the value of the data from the ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

Guide to setting up a search function with class name filtering

I am currently managing a website with multiple items, each represented by individual div elements. While all items share one common class name, they also have several other class names serving as tags to differentiate them (some tags may overlap between d ...

Angular 6 is showcasing dates in a quirky manner

In my Angular app, users can enter comments. The comments are displayed automatically with the date they were added. However, there is an odd behavior that I've noticed: When a user enters a comment, the time displayed is incorrect. (Check the ...

creating a JSON API

Seeking advice on creating a unified API for my website. Currently have distinct code for Twitter, YouTube, and Flickr services. Any suggestions on how to aggregate them by date? ...

Creating an HTML element with jQuery using the before() method

Here is the code snippet I am working with: $(document).on("click", "#add", function() { console.log("clicked"); $(this).before('<lable>'+ current +'.</label><input type="text", id="option"><br>'); ...

Adjust the dimensions of an element using Protractor

When using the getSize method, I am able to determine the size of an element but I am struggling to understand how to change its height. To provide some additional context, my goal is to verify if a user can resize a textarea element. Should I simply adju ...

Placeholder fails to appear

After implementing some jQuery validation, I wanted to display a text as a placeholder when the user skipped out of an input field without entering anything. This is the code I wrote: $('input[type="text"]').on('blur', function() { ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Virustotal API - Retrieve complete Subdomain Inventory

I am searching for a way to retrieve the complete list of subdomains for a given URL by utilizing the Virustotal API When I tested Google.com on their platform, Virustotal reported a total of 3.2k subdomains for Google.com. Visit this link for more detail ...

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...

Storing column names in an array using PL/pgSQL with PostgreSQL

function extr( tableName ) returns text[] as $$ declare columns text[]; begin execute 'select array_agg(column_name::text) from information_schema.columns where table_name = '||quote_literal(tablename)||';' into columns; return ...

Transferring a reference to an array to another function in the C programming language

I have encountered an issue while working on a program that involves passing a pointer named rgb. This pointer is initially initialized with memset to 0 and then looped through to store a 32-bit integer within specified bounds determined by height (h) and ...

I encountered a crash in my app because of an error in my Node.js backend code that was posting the accessories and slug into the database

My node.js backend code is responsible for adding the accessory and slug to the database, but I am encountering app crashes. const express=require('express'); const Category = require("../models/Category"); const slugify=require('s ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

I'm having trouble understanding why my data does not appear even though there is space allocated for it automatically

I'm facing an issue with my code that is supposed to populate a table with dynamic content using react and ant.design. Everything seems to be working fine, but the actual content is not displaying - only the space for it is created. What's happe ...

Finding the precise directory of a local JSON file for an Axios GET request in Vue.js

In my Vue project, I have prepared some dummy data for future development. The test data is stored in a `json` file, and my Vue project follows the typical structure created with Vue-Cli: My_project build config data service_general_in ...

Tips for delaying a node api's execution until a database query no longer returns null

While it may seem like an unnecessary complication, in my current scenario, it is exactly what I require. I am dealing with an API (API-1) that communicates with a third-party service. Instead of directly providing me with a response that I can send back ...