After an Ajax request to the Laravel Controller, the JSON data is displayed instead of the Datatable

Could use some guidance with ajax and json. I'm implementing an Ajax call to a Laravel Controller to fetch data from a database table called "subjects" and display it in a DataTable on a Laravel View. However, instead of the DataTable, all I see is JSON when I open the view.

Data returned in the view subjects/index:

{"draw":0,"recordsTotal":8,"recordsFiltered":8,"data":[{"id":"1","name":"Biology"},{"id":"3","name":"English Language"},{"id":"4","name":"Physics"},{"id":"5","name":"Chemistry"},{"id":"6","name":"Mathematics"},{"id":"7","name":"Mathematics"},{"id":"8","name":"English Language"},{"id":"9","name":"French"}],"queries":[{"query":"select count(*) as aggregate from (select '1' as `row_count` from `subjects`) count_row_table","bindings":[],"time":4.65},{"query":"select `id`, `name` from `subjects`","bindings":[],"time":0.41}],"input":[]}

HTML in the view /subjects/index:

<table id="subjects_table" class="table table-bordered" style="width:100%">
    <thead>
            <tr>
                <th>Id</th>
                <th>Subject</th>
            </tr>
        </thead>
        <tbody>
        
        </tbody>
    </table>

Laravel Controller code:

class SubjectsController extends Controller
{
    public function index()
    {
        $subjects = Subject::select('id', 'name');
        return Datatables::of($subjects)->make(true);
   }
}

Ajax call code:

$('#subjects_table').DataTable({
      "processing": true,
      "serverSide": true,
      "ajax": "{{route('subjects.index')}}",
      "columns":[
          {"data": "id"},
          {"data": "name"}
      ]
});

Route definition in web.php:

Route::get('subjects/', 'SubjectsController@index')->name('subjects.index');

Any assistance would be greatly appreciated.

Answer №1

For a solution, consider the following steps:

Routes

Route::get('subjects', 'SubjectsController@index')->name('subjects.index');
Route::get('getsubjects', 'SubjectsController@getSubjects')->name('subjects.get');

SubjectsController

class SubjectsController extends Controller
{
    public function index()
    {
        return view('subjects.index');
        $subjects = Subject::select('id', 'name');
        return Datatables::of($subjects)->make(true);
   }

   public function getSubjects()
    {

        return \DataTables::of(Subject::query())->make(true);

   }
}

View

    <table id="subjects_table" class="table table-bordered" style="width:100%">
    <thead>
            <tr>
                <th>Id</th>
                <th>Subject</th>
            </tr>
                </thead>
                <tbody>

                </tbody>
        </table>

<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $('#subjects_table').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route('subjects.get') }}',
            columns: [
                {data: 'id', name: 'id'},
                {data: 'name', name: 'name'},
                {data: 'email', name: 'email'},
            ]
        });
    });
    </script>

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

Converting the jQuery $.xajax loadmore feature into a custom XMLHttpRequest JavaScript function

I'm facing challenges while trying to create a XMLHttpRequest loadmore function as compared to using $.ajax. I am uncertain about what I might be missing in my code. Below is the function that is based on a previously working $.ajax version that I ha ...

PHP: A guide on validating textboxes with jQuery AJAX

How can I use jQuery AJAX to validate a textbox on focusout? The validation process includes: Sending the value to a PHP page for server-side validation Displaying an alert message based on the validation result I have only impl ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

Here is a unique version: "Exploring the process of merging with groupBy in Laravel using PHP when dealing with two arrays, one of which contains all data

https://i.stack.imgur.com/OurWm.jpg https://i.stack.imgur.com/ehn40.jpg Is it possible to merge arrays with groupBy in Laravel PHP when one array lacks attributes and the other has additional properties? This scenario involves working with two different ...

Ways to provide input parameters to a method upon clicking an element without using the HTML onclick attribute

Is there a way to pass data between pages without redirecting to the next.php page every time a button is clicked? One suggestion is to remove the onclick attribute from the button: <button class="submit-btn"></button> and use this jQuery fu ...

Retrieving data from a separate server using GWT on the client side

My dilemma involves a file called sample.xml residing on one web server, and I need to retrieve this file from a GWT application running on a separate server. Rather than making RPC calls to the GWT server to access the file through server-side proxy, I pr ...

Looping through multiple AJAX calls

I have come across numerous questions on this topic, but I am still struggling to find a solution that will make my code function correctly. There is a specific function for calling AJAX that I am unable to modify due to security restrictions. Here is how ...

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

The jQuery button function is not compatible with Google Graph

Upon review below, I have successfully created the getChart() function. It functions properly when called independently, however, it fails to display the chart when enclosed within $(document).ready(function(){...}). The file is also attached for referen ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

Monitor and retrieve live updates of links using Javascript

I am a beginner in JavaScript and recently developed a successful Chrome extension for Dubtrack. I have been struggling to find a way to make my injected script run in real-time and grab the latest YouTube music video URL. Any assistance would be greatly a ...

How can I use the jQuery library along with the Ajax method to search for listings on CraigsList?

Earlier, I attempted to query craigslist for a page but was unsuccessful in doing so. My goal is to retrieve the page from: through an ajax call, parse the html, and work with the results. For this question, my focus is solely on successfully querying an ...

The use of jQuery ajax requests is leading to a refresh of the page

I've encountered an issue with a button on my HTML page that is not associated with any form. <input type='button' id='submitter' value='add'/> There is a click handler attached to it: $('#submitter').c ...

I am experiencing difficulty in successfully transmitting a variable from my jQuery code to my PHP code

I've been attempting to pass a variable from my jQuery code to my HTML/PHP code using AJAX and POST. However, I'm encountering an error message stating "Notice: Undefined index: testData in C:\xampp\htdocs\teszt\test1.php on l ...

"Trouble with making jQuery AJAX calls on Internet Explorer versions 8 and 9

I've been searching for the answer to this problem without any luck. I have a page with jquery ajax calls to an API service. It works well in Chrome, Safari, Firefox, and IE 10, but fails in IE 9 and 8. Here is the code: $.ajax({ ...

The never-ending scrolling problem: Autoscroll refusing to halt - a perplexing conundrum in the world

I'm having an issue with my chat box continuously autoscrolling and not allowing me to scroll up. I know where the problem is, but I'm unsure of how to resolve it. Ideally, I want the chat box to autoscroll while still maintaining the ability to ...

What are the steps to ensure synchronous angular ajax calls?

function SubmitIdeaEvaluation(evaluationForm, ideaId, stageId, isEvaluated) { return $http({ url: SparkApp.FormEvaluation.SubmitIdeaEvaluation, method: "POST", contentType: "application/x-www-form ...

Safari's Failure to Execute Ajax Requests

My HTML page includes an ajax request that is functioning properly on Firefox, but does not work on Safari. While debugging, I noticed that the readystate is undefined and the status is "". Can anyone suggest why it might not be working on Safari? Javascr ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Is the integer value included in the linear progression?

I have a unique setup where each time the user clicks a 'Done' button, 20 is added to a base number, x (..-40,-20,0,20,40,60..). This updated value of x is then saved in a database and displayed in real-time using Ajax. However, I am facing a ch ...