What is the best way to send information using AJAX when combining a form submission with a global variable?

I'm currently working on a project where I need to upload a file to my server and save the filename to my database. Although I've successfully saved it to the database, I also want to save the username along with the filename. The issue is that I can't pass the username value from the blade to the controller because it's not included in the form submission for the file upload button. The username is stored as a global variable. Is there a way to send this username value to the controller through AJAX along with the form data? What changes do I need to make in my code for this to work properly? Thank you for your help!

I attempted to pass the username like this:

data: "refNumber2="+refNumber2+formData,

but unfortunately, the username value is still not being passed.

Here is the HTML code for uploading the file:

<form method="post" action="{{URL::to('/store')}} " enctype="multipart/form-data" id="frmuploadFile" class="frmuploadFile">

                            <input name="image" type="file" class="image">

                            <input type="hidden" name="_token" value="{{ csrf_token() }}">

                        <button type="submit" name="btn" id="btn-upload" class="btn btn-default col-sm-15">Upload a File</button>

                    </form>

This is the AJAX code that I'm using:

$('form').on("submit",function(event) {
                event.preventDefault();
                var formData = new FormData($(this)[0]);
                $.ajax({
                    url: "{{ url ('/store')}}",
                    type: 'POST',      
                    data: "refNumber2="+refNumber2+formData,
                    async: true,
                    cache: false,
                    contentType: false,
                    enctype: 'multipart/form-data',
                    processData: false,   
                    success: function(data){
                    }
                });                
            });//form

And here is the Controller code:

public function store(Request $request){
        $refNumber = $request->get('refNumber2');
        if (Input::hasFile('image')){
            echo "UPLOADED <br>";
            $file = Input::file('image');

            $filenameWithExt = $request->file('image')->getClientOriginalName();
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->file('image')->getClientOriginalExtension();

            $fileNameToStore = $filename.'.'.time().'.'.$extension;

            $file->move('uploads', $fileNameToStore);
            $filename = $file->getClientOriginalName();
        }

        DB::table('i_di_thread')
            ->insert(['refNumber'=>$refNumber,'message'=>$fileNameToStore]);
    }//Upload File

Answer №1

Simply include an additional hidden field within your form and assign the value of your global variable to it.

<form method="post" action="{{URL::to('/store')}} " enctype="multipart/form-data" id="frmuploadFile" class="frmuploadFile">

  <input name="image" type="file" class="image">

  <input type="hidden" name="_token" value="{{ csrf_token() }}">
  // add another hidden field here
  <input type="hidden" name="refNumber2" id="refNumber2" value="{{ your_global_variable }}">

  <button type="submit" name="btn" id="btn-upload" class="btn btn-default col-sm-15">Upload a File</button>

</form>

Answer №2

It's possible to include an additional concealed parameter in this section, such as one labeled userName.

<input type="hidden" name="userName" id="userName" value="{{Auth::user()->name}}">

Then, within your Controller, you can access it using:

$request->get('userName')

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

How can I arrange a specific array position in Vuejs according to the Id value?

<div v-for="(item, index) in gr" :key="space.id" class="val-name"> </div> After making a few modifications to the API call logic, I was able to achieve my desired outcome. However, the issue lies in the fact that ...

Exploring the integration of Ant Design Vue within HTML code

How can ant design vue be implemented in HTML? I attempted to install this library using npm and obtained the following files: antd.js, antd-with-locales.js.map, antd.js.map, antd-with-locales.min.js, antd.min.js, antd-with-locales.min.js.LICENSE.txt, ant ...

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

Only reveal a single div when hovering

I am currently working on a project that involves utilizing the Wikipedia API to allow users to search for and retrieve information from Wikipedia. I have made significant progress, but I have encountered an issue. When hovering over the "each-list" div, t ...

Converting a JSON array into easy-to-read data

I've been searching through this website for quite a while now, but I can't seem to figure out how to extract human-readable values from this JSON array. An alert displays the following: {"item1":"value1","item2":"value2","item3":"value3"} I w ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Oops! We encountered an internal server error while trying to resolve the import for "@vue/server-renderer"

Several months ago, I created a Vue 3 project using Vite and everything was running smoothly. However, today when I tried to make a small modification, an error occurred at runtime. All Vue files are showing the same error message: [vite] Internal server ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

Having trouble sending data to a Django function with Ajax request

I am currently facing an issue with my AJAX calls in Django. While fetching data works seamlessly, adding new data is resulting in an error message. Method Not Allowed (POST): /mymodels/ Method Not Allowed: /mymodels/ [17/Mar/2020 22:27:24] "POST /mymodel ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

JavaScript Click Event Not Functioning

I am attempting to create an interactive feature where clicking on any image will either reveal a clear version of the picture if it is blurred, or blur the picture if it is clear. The current issue I am facing is that when I click on a blurred image, it ...

Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach? new MutationObserver(mut =& ...

unable to transfer Vuex store information to the graph

Currently, I am facing an issue with passing my vuex store data into my apexcharts graph. Despite my efforts, it seems like the data is not being displayed correctly. Can anyone provide guidance on what I might be doing wrong? My main objective is to updat ...

Attempting to use Selenium in JavaScript to download a file with a new element called 'TransitionRejection'

I am looking to streamline the process of downloading multiple files from a website. To achieve this, I navigate through several pages to obtain the file IDs using selenium and a perl script. Since selenium does not have a built-in download function and u ...

Adjust css style based on the current time of day

I recently came across this fascinating tutorial that demonstrates an animation changing from day to night every 30 minutes. The concept is very appealing, but I began contemplating how to adapt this animation to reflect real-time changes between day and ...

What steps do I need to take to integrate Twilio's SMS service into an HTML document?

I have been searching for solutions using php and node.js (which is a derivative of js, so it should work), but I came across this library: <script type="text/javascript" src="//media.twiliocdn.com/sdk/js/client/v1.4/twilio.min.js"></script> ...

Simulated function invocation just one time

I am testing the functionality of two functions in the same file. One of the functions is supposed to call the other, and I need to verify that this interaction occurs. import * as strings from './strings'; const generateUuidSpy = jest.spyOn(st ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...

Obtain the current user's Windows username without relying on the ActiveX object

Is there a way to retrieve a client's Windows username in ASP.NET when hosted on a remote server without using an ActiveX object? I tried the following code: Response.Write("HttpContext.Current.Request.LogonUserIdentity.Name " & HttpContext.Cur ...

The dialog box in my ajax jquery MVC2 asp.net application is refusing to open

The delete dialog box does not open with my code: view: `<div id="dialog-confirm" title="Delete dialog" style="display: none;"> <p> Are you sure you want to delete the point? </p> </div>` Javascript: `option ...