Passing JSON values from a dropdown menu to be used as a route parameter in Laravel

Within my Laravel-5.8 project, I have implemented the following JSON get request code in the controller:

public function findIdentity(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $identity = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('id',$request->id)->first();
    return response()->json([
        'identity' => $identity->id
    ]);        
}  

View blade:

< script type = "text/javascript" >
  $(document).ready(function() {
    $(document).on('change', '#identity', function() {
      var air_id = $(this).val();
      var a = $(this).parent();
      var op = "";
      $.ajax({
        type: 'get',
        url: '{{ route('get.identities.all') }}',
        data: {
          'id': air_id
        },
        dataType: 'json', //return data will be json


        success: function(data) {
          console.log(data.identity);
          $('#identity_id').val(data.identity);

        },
        error: function() {

        }
      });
    });
  }); <
/script>
<div class="row" style="margin-bottom: 10px">
  <label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
  <div class="col-sm-8">
    <select id="identity" name="identity_id" class="form-control">
      <option value="">--- Select Performance Period ---</option>
      @foreach ($identities as $ids => $name)
      <option value="{{ $ids }}" {{ request('identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
      @endforeach
    </select>
  </div>
  <input type="hidden" id="identity_id" class="form-control">
  <div class="col-xs-4">
    <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
    <form action="{{ route('performance_dashboard', $id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
      {{csrf_field()}}
      <button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
    </form>
  </div>
</div>

route:

Route::get('get/findIdentity','HomeController@findIdentity')->name('get.identities.all');

In the context of all the provided codes, my objective is to pass the #identity_id as the parameter #id in the following expression:

{{ route('performance_dashboard', $id) }}

Answer №1

Unfortunately, it's not feasible to directly assign a JavaScript response to a PHP variable. However, there is a workaround that you can implement as detailed below:

<div class="col-xs-4">
    <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
    <form action="{{ route('performance_dashboard') }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
      {{csrf_field()}}
      <input type="hidden" id="identity_id" class="form-control"/>
      <button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
    </form>
  </div>
</div>

Subsequently, in the controller, you can easily fetch the indentity_id.

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

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

Utilizing Material UI Pickers and Formik to efficiently handle Date, Time, and Second components

Currently, I am developing a React application with Formik that requires the utilization of date and time pickers. The app is being constructed using Material-UI and I have been exploring the possibilities provided by Material-UI Pickers at Given my relat ...

The UseEffect hook continues to run even if the dependency (router.query) remains the same

useEffect(() => { console.log('applying filter'); const updatedFilters = { status: { values: { label: router.query.status, value: router.query.status }, }, // Add additional filter properties here... }; ...

Both the client and server sides are in sync with the latest data, yet the rendering fails to display the recent updates

The technologies I am currently utilizing include Nodejs, Express, MySQL, and EJS. My current task involves: Creating an app.get function that retrieves necessary data (posts) from MySQL, then renders a file using that data app.get("/" + element.name, f ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

Validating the length of form inputs and selected items from a dropdown menu

I have the following form and I am attempting to validate its states as follows: themeName is required and should have a minimum of 4 characters. themeLangFrom selected value cannot be the same as themeLangTo (and vice versa). I want to display a span er ...

Is there a way to execute a tanstack react query externally, as I am unable to utilize useQuery within the component?

const fetchSurveyData = useQuery(["survey"], () => getSurveyData({ page: 1, userLangCode: langCode, sortColumnName: "Date", sortColumnOrder: "DESC", country, ip, }) ); After tr ...

Integrate Tailwind CSS into the bundled JavaScript file

Is there a way to integrate tailwind css into bundle js effectively? Take a look at this example involving vue 3 and tailwind 3 https://github.com/musashiM82/vue-webpack. Upon executing npm run build , it generates 3 files: app.js ABOUTPAGE.js app.6cba1 ...

Issue: The property 'top' cannot be read as it is null

I'm trying to access the top of my footer, but I keep encountering this error message: Cannot read property 'top' of null Here is the HTML code: <footer class="footer" role="complementary" id="myfooter"> </footer> And in jQuer ...

Designated location for downloading specified by the user

I've been searching for a while now and I can't seem to find a satisfactory answer. Essentially, I have a website where users can input values and download a specific file based on those values. Everything is functional, but I want to give the u ...

What are some strategies for improving the speed of searching through an array of objects?

I've been exploring more efficient ways to search through an array of objects as my current approach is too slow. The array I'm working with has the following structure: [ { fname: 'r7942y9p', lname: 'gk0uxh', em ...

Using JavaScript to extract information from a local JSON file

I am currently working on developing an application that can function offline. My data is stored in a local JSON file and I am looking to create a filter for this data without having it hardcoded in a JavaScript file. The examples I have come across so far ...

Resource for building user interface components in Javascript

I need assistance with implementing a feature that involves scrolling through different text blocks and corresponding images. Users should be able to select a specific text block and have the associated image on the right scroll into view, similar to a car ...

Automatically notifying users via email about console errors in JavaScript

My exploration on this question and useful links: How to send console messages and errors to alert? jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined The coding example: function handleError(evt) { if (ev ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

What is the best way to keep vue-meta up to date when the route or URL

The issue I am facing is that the meta data on my website does not update when the route changes. Even though the route has a watch function that updates the view correctly, the metaInfo() method from vue-meta fails to keep up with the changes. Below is an ...

Implementing Jquery Ajax Autocomplete Feature in JSP

I am currently exploring a tutorial on jQuery autocomplete using remote data. In my JSP page, I have the following code snippet: (getData.jsp) Department t = new Department (); String query = request.getParameter("q"); List<String> ...

Click Event for Basic CSS Dropdown Menu

My goal is to develop a straightforward feature where a dropdown menu appears below a specific text field once it is clicked. $(".val").children("div").on("click", function() { alert("CLICK"); }); .container { display: inline-block; } .val { d ...

Creating interactive PDF files using ReactJS

Is there a way to create a PDF using React that supports styling and allows the content to be hidden on the page? I need to have a link in my app that, when clicked, generates a PDF and opens it in a new tab. I've tried out various packages but none s ...