I have in my view one input type "file", so I would like to get this file with jquery and send to my controller in Laravel, but, I don't see this file in debug
<form onSubmit="return false;" method="post" id="myForm" enctype=“multipart/form-data”>
#csrf
<label for="input-file-max-fs">Foto do perfil</label>
<input type="file" name="foto" id="foto" class="dropify #error('foto') is-invalid #enderror" data-max-file-size="3M" />
</form>
in the JS
$('.update).on('click', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dados = {
foto: $('input[name=foto]').val(),
.....
}
$.ajax({
method: 'PUT',
dataType: 'JSON',
url: '../perfil/editarusuario/',
data: dados,
success: function(res) {
console.log(res);
}
});
})
and in my Controller I trying to get the file, but no success
$file = $request->file('foto');
$file = $request->hasFile('foto')
$file = $request->file('foto')->isValid()
none of theses work
You should use "new FormData()" and "contentType",
here is the answer to this;
https://stackoverflow.com/a/21045034/14843602
Related
Since a lot of days I am trying to upload file in the server I got 405 methods not allowed error in live server:
This is my view:
HTML & javascript
#extends('layouts.app')
#section('content')
form id="uploaddiamond" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
#csrf
<div class="col-md-6">
<div class="block">
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 control-label">Upload Diamond <span class="required">*</span></label>
<div class="col-md-9">
<input required="" type="file" name="result_file" id="result_file" />
</div>
</div>
<div class="btn-group pull-right">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
#endsection()
#section('javascript')
<script>
$("#uploaddiamond").on("submit",function(e) {
e.preventDefault();
console.log('tst');
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
});
var file_data = $('#result_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "{{ route('diamond') }}", // point to server-side PHP script
data: form_data,
type: 'POST',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false,
success: function(data) {
console.log(data);
}
});
});
</script>
#endsection()
This is my web route:
Route::get('/imageview','ImageController#index')->name('getimage');
Route::post('/postDiamond','ImageController#postDiamond')->name('diamond');
This is my controller:
public function index(){
return view('Image/imgupload');
}
public function postDiamond(Request $request){
dd($request->file('file'));
$supplier_name = $request->supplier_name;
$extension = $request->file('file');
$extension = $request->file('file')->getClientOriginalExtension(); // getting excel extension
$dir = 'assets/files/';
$filename = uniqid().'_'.time().'_'.date('Ymd').'.'.$extension;
$request->file('file')->move($dir, $filename);
}
I don't why this code is not working cause this code works in localhost but, not working in Linux hosting:
Can someone help do I have did a mistake on version something
server current PHP version:7.3.17
laravel PHP version:7.1.10
This is my server error image please check:
enter image description here
enter image description here
Well I have just tested this code on live server and it's working fine. If this code still doesn't work for you then you need to check permissions on server side for some files like web.php etc...
$(document).on('click','#submit_button', function(e){ //#submit_button id on submit button
e.preventDefault();
var formData = new FormData(this.form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
method: 'POST',
url: '{{ route("diamond") }}',
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
Be sure to remove #csrf from your <form> tag.
In controller just dd(request()->all()); and see what you get
Hey everyone Im trying to upload a file with ajax. I am also passing an username to get inserted into a database. In previous forms I've been using vuejs to run a fiction on submit rather than actually submitting the form with php. As I json encode everything and it requires no refresh.
heres my form the problem is I cant get the file upload to work.
<div id="app">
<form role="form" onsubmit="return false">
<div class="form-group">
<label>Username</label>
<input type="text" placeholder="Username" v-model="userName" name="userName" class="form-control>
</div>
<div class="form-group">
<label>File</label>
<input type="file" #change="processVideoFile($event)" id="uploadVideoFile">
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
userName: '',
uploadVideoFile:''
methods: {
processVideoFile: function() {
this.uploadVideoFile=$('#uploadVideoFile').val();
},
addTemplate: function(){
this.sub=true;
var jsonString = JSON.stringify({
uploadVideoFile: this.uploadVideoFile,
userName: this.userName
});
if(this.userName!=''){
$.ajax({
url: 'addTemplateBackend.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(data){
alert('error');
},
success: function(data){
console.log(data);
alert('success');
}.bind(this)
});
}
},
}
});
</script>
add templates backend
<?php session_start(); ob_start();
require_once('database.php');
$requestBody = file_get_contents('php://input');
$requestJSON = json_decode($requestBody);
$data=json_encode($requestJSON);
echo $data;
move_uploaded_file($requestJSON->uploadVideoFile, 'www.somesite.com/braiden/braintree/');
?>
I'm trying to add an image to a post with Ajax / Laravel 5.4.
This is my HTML:
<form class="comments-form" action="/upload/comments/{{$post->id}}" method="post" data-id ="{{$post->id}}" enctype="multipart/form-data">
#csrf
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
Here is the Ajax code:
$('.add-comment').click(function(){
var comment_data = $('.comments-form').serialize();
var post_id = $('.comments-form').data('id');
var formData = new FormData('.comments-form');// i think here is problem
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,formData,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
This doesn't work – what am I doing wrong?
The FormData constructor takes a form not a string(you passes a css selector)
var formData = new FormData($('.comments-form').get(0));
If you use FormData in this way all fields in the form will be automatically added to the FormData object.
If there are items outside of the form fields that needs to be sent use the append method
formData.append('comment_data', $('.comments-form').data('id'));
When passing a FormData object to jQuery ajax you pass it alone and add processData and contentType set to false
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: formData,
contentType: false,
preocessData: false,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
If you want to store data using ajax.. you shouldn't need to put your action in your form component
<form class="comments-form" data-id ="{{$post->id}}">
{{ csrf_field() }}
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
</form>
I think if you want to submit your form, better to use jquery submit method
$('.add-comment').submit(function(){
var post_id = $('.comments-form').data('id');
var comment_data = new FormData($(".comments-form")[0]);
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,
dataType: 'json'
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
you can solve it as the following:
var formData = new FormData($("#FormId")[0]);
$.ajax({
url: '/upload/comments/' + post_id,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'application/json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function (data, textStatus, jqXHR) {
console.log(data);
$('.all-comments').append(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error');
}
});
return false;
the formData variable contains all data of the form if you want to send the post id with the data sent you can put hidden field inside form called post id
like this
<input type="hidden" name="post_id" value="{{$post->id}}">
and then apply the above code
I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.
HTML:
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
<input type="button" value="Submit" onclick="uploadPhoto();" />
</form>
JS:
var formData = new FormData();
formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('.files-data'), function(i, obj) {
jQuery.each(obj.files, function(j, file){
formData.append('files[' + j + ']', file);
});
});
jQuery.ajax({
url: 'mbAlbumUploader.ajax_url,'
type: 'post',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
alert(response.files);
}
});
PHP function:
function uploadPhoto() {
$fileName_str = '';
foreach($_FILES['photo_upload']['name'] as $f=>$name) {
$extension = pathinfo($name, PATHINFO_EXTENSION);
$fileName_str .= $name . ', ';
}
die(wp_json_encode(array(
'files' => $fileName_str;
)));
}
What I am doing wrong?
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.
HTML
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
JavaScript
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('album_title', jQuery('#album_title').val());
data.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
PHP (upload.php)
You can Access your files from $_FILES global.
I have an individual html form for uploading photo on Laravel's blade and I am trying to post the image to the Controller.
The Html form looks like:
<form id="fileForm" enctype="multipart/form-data">
<input type="file" id="fileInput" name="fileInput" style="visibility: hidden"/>
<input type="button" value="submit" id="ajaxSubmit" hidden />
</form>
And in (document.ready):
jQuery('input[type=file]').change(function() {
jQuery('#fileForm').submit();
});
jQuery('#fileForm').on('submit',(function(e) {
e.preventDefault();
jQuery.ajax({
url: '',
type: 'POST',
data: new FormData(jQuery(this)[0]),
processData: false,
success: function (data) {
},
complete: function() {
}
})
}))
When I dd(Input:all()); on the controller, it shows this and so on:
However, dd(Input::file('fileInput)) returns null.
When I try dd(Input::hasFile('fileForm')); (which I feel it is not correct), it returns false