upload image in Laravel before submitting form using ajax - javascript

I have written some watermark code in Laravel and it is working fine. But now I want to show the preview before submitting the file. But I am getting error "POST 419 (unknown status)"
My view source code is
<form class="form-horizontal" method="POST" action="{{ route('announcement.store') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<label for="description">Description</label>
<textarea id="my-editor" class="textarea" name="description" ></textarea>
<label for="image">Featured Image</label>
<input type="file" id="image" name="image">
<button type="submit" class="btn btn-success">Submit</button>
</form>
Javascript code
$(document).ready(function() {
$("#image").change(function(e) {
var image = $('#image').val();
$.ajax({
type: 'POST',
url:'{{url('/my-admin/imageupload')}}',
data: {image:image},
success: function( msg ) {
alert(msg);
},
error: function( data ) {
alert(data);
}
});
});
In this code, when I change the image I get error. I have done some watermark on image and save that image in folder. Now, I need to show that image on preview before submitting the form.

Image will not be sent with this "var image = $('#image').val();" piece of code while using ajax request as you need to use data = new FormData(); for image.

You missed _token as data to submit on ajax, so change the data to
data: {
"_token": "{{ csrf_token() }}",
"image":image
},

I have successfully uploaded the image by this code.
$("#image").change(function(e) {
var data = new FormData();
data.append('image', $('input[type=file]')[0].files[0]);
data.append('_token', "{{ csrf_token() }}");
$.ajax({
url:'{{url('/my-admin/imageupload')}}',
type: 'POST',
data : data,
enctype : 'multipart/form-data',
contentType: false,
processData: false,
success: function( data ) {
var baseUrl = "{{asset('')}}";
var imageUrl = baseUrl + data.msg;
$('#changeimage').html('<img src="'+ imageUrl +'" height="120px" width="150px">');
},
error: function() {
alert('unable to insert watermark on image');
}
});
});

Related

I get an empty error when submitting multiple forms with file uploads with ajax in laravel

my problem is while posting multiple forms with ajax in laravel, I am sending the form data without any problem, but I cannot send the file.
File is empty error. I've been dealing with this for 2 days, there is no method I haven't tried, please help me.
Apart from that, I added multipart to the form, but it still didn't work, I'm sharing my codes with you.
Sorry for my bad english.
I want it to upload 2 photos in the normal 4th form until the createProduct3 form, I tried to get them by doing the normal new formData() and I tried otherwise and I couldn't succeed.
It sends it to Laravel server side as [Object File].
My Form
<form class="form" id="createProduct4" method="POST" action="">
<input type="file" class="upload-box-title" id="urun-fotografi" name="urun_fotografi" value="Fotoğraf Seç">
<input type="file" class="upload-box-title" id="urun-dosyasi" name="urun_dosyasi" value="Dosya Seç">
</form>
My blade ajax:
function createProducts()
{
var dataString = $("#createProduct1, #createProduct2, #createProduct3, #createProduct4").serialize();
let photo = document.getElementById("urun-dosyasi").files[0];
let photo2 = document.getElementById("urun-fotografi").files[0];
console.log(photo,photo2);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
data: dataString+"&urun_dosyasi="+photo+"&urun_fotografi="+photo2,
success: function( data ) {
},
error: function(xhr)
{
console.log(xhr);
}
});
}
Server Function
public function createProduct(Request $request)
{
$file = $request->file('urun_dosyasi');
$file2 = $request->file('urun_fotografi');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filename2 = $file2->getClientOriginalName();
$extension2 = $file2->getClientOriginalExtension();
echo $filename,$extension."2. doc: ".$filename2.$extension;
}
Use multipart/form-data when your form includes any <input type="file"> elements :
<form ... enctype="multipart/form-data">
Ajax :
var form = $('#createProduct4')[0];
var data = new FormData(form);
$.ajax({
url: "{{ route('user.product.create') }}",
type: "POST",
enctype: 'multipart/form-data',
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});

Php Ajax file upload, always getting undefined index error

Submitting file through ajax not working. I have followed other posts to create this but it appears formdata is not containing the file as a result i always get the error of undefined index 'image'
<form enctype: 'multipart/form-data'>
<div class="add_category">
<label style="font-size:20px;">Add categories</label>
<input type="text" name="category" id="category" placeholder="Enter Here" style="border-style:solid;height:30px;">
<label style="font-size:20px;">Choose image</label>
<input type="file" id="file" name="image" style="border-style:solid;height:25px;">
<button name="add_category" type="button" onclick="addcategory()" >ADD Category</button>
</br>
</br>
</div>
</form>
function addcategory(){
//var1=document.getElementById("category").value;
var formData = new FormData();
formData.append('image', $('input[id=file]')[0].files[0]);
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
enctype: 'multipart/form-data',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
alert(data);
}
});
}
performcategoryserver.php:
<?php
$imagename=$_FILES['image']['name'];
echo($imagename);
?>
This always return undefined index image error ,please help.
Change
<form enctype: 'multipart/form-data'>
to
<form id="myform" enctype= 'multipart/form-data'>
Change your function to:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
data : formData,
async : false,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType:"json",
success : function(data) {
alert(data);
}
});
}
Your form tag opened in wrong way firstly can you fix that and try again ?
<form enctype: 'multipart/form-data'>
Should be
<form method="post" enctype="multipart/form-data">
Finally found the working code,
Changed this:
<form id="myform" enctype= 'multipart/form-data'>
Changed this:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'performcategoryserver.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
alert(xhr.responseText);
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
}

Upload a file with Ajax, jQuery and Laravel [duplicate]

This question already has answers here:
How to upload a file using jQuery.ajax and FormData
(2 answers)
Closed 3 years ago.
I am trying to upload a form with jQuery and Ajax using Laravel as server side code, my form is:
HTML:
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Comprobante</label>
<input type="file" name="file" class="form-control" id="file" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nombre</label>
<input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
</div>
</form>
jQuery, Ajax:
$( 'body' ).on( "submit", 'form', function() {
event.preventDefault();
var formData = new FormData();
formData.append("file", $('#file')[0].files[0]);
formData.append("name", $('#name').val());
var formData = $(this).serialize();
$.ajax({
type:'POST',
url:"{{ url('/accountability/store') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
success:function(html)
{
alert('stored!');
}
});
});
Laravel:
$extension = $request->file('file')->getClientOriginalExtension();
$filename = $request->rut.'_rendicion_'. date('d_m_Y_h_i_s') .'.'.$extension;
Storage::disk('dropbox')->putFileAs(
'/intranet_jisparking_archivos_web/',
$request->file('file'),
$filename
);
The problem is that it says that
Call to a member function getClientOriginalExtension() on null
But I do not understand why? because I am uploading the file with this $('#file')[0].files[0] in the jQuery. It looks like $request->file('file') is empty, how can I fix it?
Thanks!
Try this:
var formData = new FormData();
var file = $('#file').prop('files')[0];
formData.append('file', file);
formData.append('other_variable', $('#other_variable').val());
// Don't use serialize here, as it is used when we want to send the data of entire form in a query string way and that will not work for file upload
$.ajax({
url: '{{ url("your_url") }}',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// Do what ever you want to do on sucsess
}
});
In controller method, you will get the file like:
$file = Input::file('file');

How to solve this jQuery ajax post method undefine index problem while uploading images?

I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.

How to upload image using ajax request

I'm search in the internet for a solution. I find some of them but they didn't work for me. Basically I have an input form on a laravel project where I want to upload an image with ajax request.
On the Get request instead of sending the image is sending the following parameter value [object%20FormData]
I know that I'm doing something wrong but I don't know what it is. Can anyone help me? Here is my Html code
<form class="form-horizontal" id="upload" enctype="multipart/form-data" action="{{{ URL::route('upload') }}}" autocomplete="off" onsubmit="return false">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="file" name="image" id="image" />
<button type="button" id="upload_image_btn" class="btn btn-default">Upload!</button>
</form>
And here is my ajax code
var image = $('#image')[0].files[0];
formdata = new FormData();
formdata.append( 'image', image );
formdata.append( 'action', 'image' );
$.ajax({
type: "GET",
url: '{{{ URL::route('upload') }}}',
data: formdata,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors, function (key, data) {
$.each(data, function (index, data) {
$(".upload_error").text(data);
})
})
}
});
Can anyone help me to find what I'm doing wrong? Thank you
SOLUTION: as the comment says, I changed the GET request of ajax to POST and it work. Thank you for your help

Categories