My form:
<form enctype="multipart/form-data" method="post" id="createProduct">
<input required name="name" type="text">
<textarea name="description"></textarea>
<input id="imageToUpload" type="file"name="images[]" multiple/>
<input type="submit" value="submit"/>
</form>
My Script :
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#createProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = "";
var url = "";
var method = $(this).attr('method');
var formData = new FormData;
for(var i = 0; i < images.length; i++){
formData.append(images[i].name, images[i])
}
var myData = {
name: $(this).find("[name='name']").val(),
description: $(this).find("[name='description']").val(),
images: formData
}
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: myData,
cache: false,
contentType: false,
processData: false,
success: function(data){
console.log(data);
window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
My Controller:
public function store(Request $request){
$input = Input::all();
return Response::json([
'message' => 'Product Created Succesfully',
'data' => $input
], 200);
How to send data(with images) from form to ajax
How to retrieve data(with images) from ajax to store(API) function in the controller.
so that i can process and save the files.
via Mukil