Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this.

Below is an example of my controller:

public function index(Request $request)
{
    if($request->has('search'))
    {
        $student_data = \App\Student::where('name','LIKE','%'.$request->search.'%')->get();
    }
    else
    {
        $student_data = \App\Student::all();
    }

    return response()->json(array('student_data' => $student_data));
}

Answer №1

Avoid using ajax, instead directly display the json on the page as a javascript variable

public function show(Request $request)
{
    if($request->has('search'))
    {
        $students_data = \App\Student::where('name','LIKE','%'.$request->search.'%')->get();
    }
    else
    {
        $students_data = \App\Student::all();
    }
     $students_data = $students_data->toJson();


    return view('show',compact('students_data'));
}

In your view, you can simply use

<script>
var students_data = {{$students_data}};
</script>

Answer №2

The best way to accomplish this task is by utilizing an ajax request. If you prefer using vanilla JavaScript, you can make use of the Fetch API

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

In your specific scenario, you will be able to retrieve the data_siswa array by accessing myJson.data_siswa

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

Is the data missing in the initial request?

After creating a function that returns an object with mapped values, I encountered an issue. The second map is undefined the first time it runs, causing my vue.js component to display data from the first map but not the cutOff value. Strangely, when I re ...

Struggling to link variables and functions to an angularJS controller

When using the $scope object to bind functions and variables, and making changes accordingly in HTML, the code works fine. But when using a different object, it doesn't work as expected. Here is an example of a working code snippet: ...

Challenges with managing jQuery's .blur() and .focus() events

I am encountering an issue with a form I have created that contains several input fields. When a user clicks on any of the input fields, a hidden div appears with various options related to that field. The user can then select an option from the div, which ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Convert HTML to JSON using a selection

After selecting multiple values in the alpaca form using a select ui element, I encounter an issue when saving the form. When I use JSON.stringify(val) to generate the JSON data, it only includes the ids of the selected elements. However, I would like the ...

Convert the generic primitive type to a string

Hello, I am trying to create a function that can determine the primitive type of an array. However, I am facing an issue and haven't been able to find a solution that fits my problem. Below is the function I have written: export function isGenericType ...

Trouble with implementing web methods through AJAX communication channel

my .cs code is auth_reg.aspx.cs (breakpoint shows the method is never reached) [WebMethod] public void ImageButton1_Click() { string strScript = "<script language='JavaScript'>alert('working')</script>"; Page.Regis ...

Using Reactjs to set state with a dynamically generated key-value pair

I have a dynamic object in props that I need to transfer to state @setState key: val values: another_key: value @props.data.option: @props.data.value Unfortunately, the above method does not work as expected. I have come up with an alternativ ...

Ways to parse the data from a response received from an Axios POST request

After sending the same POST request using a cURL command, the response I receive is: {"allowed":[],"error":null} However, when I incorporate the POST request in my code and print it using either console.log("response: ", resp ...

Converting Angular object into an array: A step-by-step guide

In Angular, I have retrieved an object that contains the following information: quiz.js:129 m {$promise: Promise, $resolved: false} 439: "https://mysite.no/sites/default/files/styles/quiz_large/public/fields/question-image/istock_000059790188_large.jpg ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

An ambient module will not be successfully resolved through a relative import operation

As per the typescript documentation (https://www.typescriptlang.org/docs/handbook/module-resolution.html): A relative import is resolved in relation to the importing file and does not resolve to an ambient module declaration. However, it also states: ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...

What causes errors in jQuery ajax jsonp requests?

"fnServerData": function( sUrl, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "url": sUrl, "data": aoData, "success": fnCallback, "error":function(msg){ ...

What prevents certain scenarios from being encapsulated within a try/catch block?

Just attempted to handle ENOENT by using a naive approach like this: try { res.sendFile(path); } catch (e) { if (e.code === 'ENOENT') { res.send('placeholder'); } else { throw e; } } Unfortunately, this method is ineffectiv ...

What is preventing me from retrieving the values of selected options in jQuery when clicking on an option?

I have a select menu with the following options. <select name="assigneeSelect" id="{{this.commonID}}" class="custom-select sources" key="{{this.id}}" placeholder="{{this.assignee}}"> <option v ...

Leveraging jQuery alongside HTML5 Video

I have a website that offers live streaming services. I wrote some code specifically for iPads which successfully plays the stream: window.location = 'http://<?php echo DEVSTREAMWEB; ?>/<?php echo $session_id;?>/'+camerahash+'/p ...