Tips for fixing the "500 (Internal Server Error)" issue in Laravel with ajax

When utilizing AJAX to fetch route data, I encountered an issue.

I aim to create a Dynamic Select that, based on the selected "Faculty," displays the corresponding "programs" linked to that faculty.

This is my route:

Route::get('selectprogramas/{id}', 'SyllabusController@getProgramas');

This represents the Program model:

class Programa extends Model
{
    protected $table = 'Programas';

    protected $fillable = ['nombre', 'perfil_profesional', 'competencias', 'facultad_id', 
    'perfil_profesional'];

    public function selectprogramas($id){
        return Programa::where('facultad_id', $id)->get();
    }

}

This is the controller function:

public function getProgramas(Request $request, $id){
        if($request->ajax()){
            $programas = Programa::selectprogramas($id);
            return response()->json($programas); 
        }
    }

The following HTML snippets show the two selects (made with Laravel Collective):

<div class="form-group col-9 font-weight-bold">
        {{ Form::label('facultad', 'Facultades:') }}
        {{ Form::select('facultad', $facultades, null, ['class' => 'form-control', 'id' => 'facultad']) }}
</div>

<div class="form-group col-9 font-weight-bold">
        {{ Form::label('programa', 'Programas:') }}
        {!! Form::select('programa', ['placeholder'=>'Selecciona'], null, ['id'=>'programa']) !!}
</div>

Below is my JavaScript code:

$("#facultad").change(function (event){
    console.log("Entered!");
    $.get("../selectprogramas/" + event.target.value ,function(response, facultad){
        $("#programa").empty();
        for(i=0; i<response.length; i++){
            $("#programa").append("<option>"+response[i].nombre+"</option>");
        }
    });
});

The error I am encountering can be seen here: https://i.sstatic.net/Lv2b4.png

Answer №1

issue resolved! Applied modification to the controller function

public function displayCourses(Request $request, $id){
    if($request->ajax()){
        $courses = Course::where('faculty_id', $id)->get();
        return response()->json($courses); 
    }
}

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

Implementing Java script for onkeypress event in a search bar that does not require a button

Currently utilizing this javascript to trigger an event on key press: function myFunction() { if (window.event || window.event.keyCode == 13) { changeSource(); } } function changeSource(){ document.getElementById("frame1").src="Log-In. ...

Guiding motion of a parental container using a button

This seems like a fairly straightforward task, but I'm getting a bit frustrated with it. Is there a way to move an entire div by simply holding down the mouse button on a particular button? let container = document.getElementById('abo ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

Creating a user interface to display different game options using Hooks (Developing an interactive rock-paper-scissors game)

I'm currently experimenting with React.js hooks while creating a new version of the classic game "Rock Paper Scissors." I'm facing an issue where the winner is not evaluated immediately after pressing the respective button. Below is a snippet of ...

Ensuring the cookie remains active throughout various subdomains

After implementing code to set a cookie on example.com, I noticed an issue with it carrying over to the subdomain dogs.example.com. <script> document.cookie="cid1={{utm_campaign}}; path=/;" </script> The {{}} is part of Google-Tag-Manager s ...

Adding additional text will not render d3.js' output

I'm struggling with a simple issue here, My goal is to add a div to my svg element containing text. I have written the code for this and in the DOM, it shows that the svg has the correct class attached along with the desired text. However, the text i ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

Secure your desktop application with OAuth by enabling HTTPS on localhost

I am currently in the process of developing a desktop application that integrates with Spotify's oauth api using the implicit grant flow as outlined here: My plan is to incorporate an "Authenticate" button, which when clicked will open the user' ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

Trigger Google Analytics event when file is downloaded from server

Here is a helpful resource on sending events to Google Analytics via API server sided: Send event to Google Analytics using API server sided An email containing a download link has been sent to a customer: Hello, Please access your product through thi ...

What is the best way to choose all elements from an array based on their key and then combine their values?

Currently, I am working on an application that allows users to read articles and take quizzes. Each article is assigned to a unique category with its own _id. Quiz attempts are stored in a separate table that references the articles, which in turn referenc ...

Running `npm install npm` results in encountering gyp ERR and npm ERR

Why am I encountering this peculiar error message when executing sudo npm install npm? This issue seems to crop up occasionally with other modules as well! Error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a7b7a6ad ...

What is the reason for this Javascript regular expression only successfully matching two out of three identical strings when filtering?

To better illustrate my question, I would like to reference the following link: http://codepen.io/anon/pen/mRxOEP Here are three seemingly identical inputs from customers: <span class="customer_country" id="SW1">, Switzerland</span> <span ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

ajax begins to experience slow response times

As time passes with the page open, the performance of this ajax request deteriorates or stops working altogether. $.ajax({ type: "POST", url: "atuamae.org/send.php", data: dataString, success: function() { showmessages() //could mak ...

Utilize the $match array within a MongoDB query in a Laravel raw query

Working with mongodb in Laravel using the jenssegers driver, I have 3 documents like this in my database: { "_id" : ObjectId("594dd540bb7de924c0005583"), "cliente" : "Luis", "tipo" : "Luis", "paquete" : "Luis", "fecha" : null, "fechaE" : null, "con ...

Pass the value of a button to jQuery AJAX using the onclick() function

Can a value be passed from a button to Jquery AJAX using the onclick function? I attempted to use this code, but it doesn't seem to be working. Nothing is showing up in the console log. HTML <button type="button" class="hapus_krs" onclick="hapus_ ...

Ways to display JSON objects containing nested key-value pairs

In my JSON structure, each Mealplan includes a key and a corresponding value which is an object called meal. id: 1, mealsPerWeek: { Monday: { id: 4, name: "Burger", }, Tuesday: { id: 3, name: "Salad&qu ...

Bootstrap does not have the ability to alter the selected value of a select element

When a user selects a filter from the dropdown menu and clicks the search button, the selected value reverts to the first option instead of staying as the last chosen option. In my controller, I send the selected filter to the view using ViewBag. This is ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...