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