Angular upload return empty object - php

I tried to upload a file via api to server.
function uploadUsing$http(file) {
file.upload = Upload.http({
url: 'api/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: file
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
If console.log(file), there is image data, but when i send the request to server i get an empty array.
server function:
public function uploadAPI(Request $request)
{
$image = $request->file('file');
dd($image); ---------> return []/null
return response()->json('upload hit server');
}
What's the problem here? Thanks!!

Have you tried using
Upload.upload({
url: 'upload/url',
data: {file: file, 'param1': $scope.param1}
});
Instead?

Related

Request data of AJAX POST is null in Laravel Controller

I'm trying to send via AJAX data, I'm doing a post and then receiving it on the laravel controller.
I'm getting an error that the data is null.
I tried multiples ways to fix it but I'm not able to figure out how to do it.
Ajax:
$(document).ready(function () {
$('table tbody').sortable({
update: function (event, ui) {
$(this).children().each(function (index) {
if ($(this).attr('data-position') != (index + 1)) {
$(this).attr('data-position', (index + 1)).addClass('updated');
}
});
saveNewPositions();
}
});
});
function saveNewPositions() {
var positions = [];
$('.updated').each(function () {
positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(positions);
$.ajax({
url: 'cursos',
method: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(positions),
contentType: "application/json; charset=utf-8",
traditional: true,
})
}
Laravel Controller:
public static function updateOrder(Request $request)
{
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
Doing a dd of the request, I receive this:
I fixed it using $request->toArray() instead of $request->positions directly

how do i send data to php from AngularJS controller?

I'm suffering a lot trying to do this, in words:
Trying to send a token to a myfunction.php so it can do it's job, then make it return 2 variables so I can use em in my Javascript controller (Made with angularJS).
So far i heard I should use $http, but I can't understand how I should do this
create an angularjs service and use it in your controller.
here is the service which can provide Create, read, write and delete functionality:
app.service("MainService", ['$http', function ($http) {
this.getItems = function (url) {
return $http.get(url);
};
this.getItem = function (id, url) {
return $http.get(url + "/" + id)
};
this.post = function (itemToCreate, url) {
var request = $http({
method: "post",
url: url,
data: itemToCreate
});
return request;
};
this.put = function (id, itemToChange, url) {
var request = $http({
method: "put",
url: url + "/" + id,
data: itemToChange
});
return request;
};
this.delete = function (id, url) {
var request = $http({
method: "delete",
url: url + "/" + id
});
return request;
};
}]);
next add this service as a dependency to your controller and use it's methods like this:
app.controller("MyCtrl", ['$scope', '$rootScope', '$timeout', 'MainService', function ($scope, $rootScope, $timeout, MainService) {
//Get All Items::
$scope.GetItems = function () {
var getAllItems = MainService.getItems("YOUR_API_URL_FOR_GET_ITEMS");
getAllItems.then(function (response) {
$scope.items = response.data;//use items with ng-repeat in you html code
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Create New Item::
$scope.Create = function () {
//CREATE an Object and send it via post request. for example:
var category = new CategoryObject($scope.Title, $scope.Description);
var promisePost = MainService.post(category, "YOUR_API_URL_FOR_Post_Item");
promisePost.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Edit an Item::
$scope.Edit = function () {
//CREATE an Object:
var category = new CategoryObject($scope.Title, $scope.Description);
//Then set it's Id
category.Id = $scope.CategoryId;
var promisePut = MainService.put($scope.CategoryId, category, "YOUR_API_URL_FOR_Put_Item");
promisePut.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Delete an Item::
$scope.delete = function (id) {
var promiseDelete = MainService.delete(id, "YOUR_API_URL_FOR_Delete_Item");
promiseDelete.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
}
}]);

Remove file dropzone js laravel error 500

I'am using dropzone js to upload multiple images (dropzone programmatically).
Upload files, it's ok.
But when I remove a file, some error occurred:
500 Internal Server Error (Method App\Modules\Product\Controllers\ProductController::delete does not exist - I don't have delete() method in controller - why?).
Cannot read property 'removeChild' of null
My route
Route::post('/adminks/products/delete/dropzone', 'ProductController#deleteImageDropzone')->name('be.delete.dropzone');
My Controller
public function deleteImageDropzone(Request $request) {
$image = $request->filename;
ProductImage::where(['image_name' => $image, 'model' => 'Product', 'module' => 'Product'])->delete();
$path = public_path().'/uploads/images/product/product/'.$image;
if (file_exists($path)) {
unlink($path);
}
return $image;
}
My JS
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzone_images", {
url: "{{ route('be.upload.dropzone') }}",
sending: function (file, xhr, formData) {
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var code = '{{ $code }}';
formData.append('code', code);
},
paramName: 'others_image',
addRemoveLinks: true,
acceptedFiles: '.jpeg,.jpg,.png,.gif',
dictRemoveFile: 'Xóa ảnh',
init: function() {
this.on("removedfile", function(file) {
var name = file.upload.filename;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
type: 'POST',
url: '{{ url('/adminks/products/delete/dropzone') }}',
data: { filename: name },
success: function (data){
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
});
}
});
Any solution? All comments are respected!
Thanks so much!

passing custom variables to formstone

I'm using formstone drag and drop file upload in my ajax powered form. using $(".uploadImage").upload("start") and $(".uploadDocs").upload("start") for initializing upload section for image and document separately after ajax function response. Each function working but I want to pass a custom variable, something like folder name to formstone and create a folder with that name and upload image and doc to that folder. how to do that?
Ajax function in which the insertion happens and return the id
$.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("start",postData: {"ideaId":10});// sending custom value to formstone, which is not working as of now
$(".uploadDocs").upload("start",postData: {"ideaId":10});
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Formstone initialization
Formstone.Ready(function() {
$(".uploadImage").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
//postData: {"ideaId":50} // this is working. but don't want this here
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
$(".uploadDocs").upload({
maxSize: 1073741824,
beforeSend: onBeforeSend,
autoUpload: false,
}).on("start.upload", onStart)
.on("complete.upload", onComplete)
.on("filestart.upload", onFileStart)
.on("fileprogress.upload", onFileProgress)
.on("filecomplete.upload", onFileComplete)
.on("fileerror.upload", onFileError)
.on("queued.upload", onQueued);
});
function onCancel(e) {
console.log("Cancel");
var index = $(this).parents("li").data("index");
$(this).parents("form").find(".upload").upload("abort",
parseInt(index, 10));
}
function onCancelAll(e) {
console.log("Cancel All");
$(this).parents("form").find(".upload").upload("abort");
}
function onBeforeSend(formData, file) {
console.log(formData.get("ideaId")); // here i need the posted data. currently its not getting here
formData.append("ideaId", ideaId);
return ((file.name.indexOf(".jpg") <= -1) && (file.name.indexOf(".png") <= -1)) ? false : formData; // cancel all jpgs
}
function onQueued(e, files) {
console.log("Queued");
var html = '';
for (var i = 0; i < files.length; i++) {
html += '<li data-index="' + files[i].index + '"><span class="content"><span class="file">' + files[i].name + '</span><span class="cancel">Cancel</span><span class="progress">Queued</span></span><span class="bar"></span></li>';
}
$(this).parents("form").find(".filelist.queue")
.append(html);
}
function onStart(e, files) {
$(this).parents("form").find(".filelist.queue")
.find("li")
.find(".progress").text("Waiting");
}
function onComplete(e) {
console.log("Complete");
// All done!
}
function onFileStart(e, file) {
console.log("File Start");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]")
.find(".progress").text("0%");
}
function onFileProgress(e, file, percent) {
console.log("File Progress");
var $file = $(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$file.find(".progress").text(percent + "%")
$file.find(".bar").css("width", percent + "%");
}
function onFileComplete(e, file, response) {
console.log("File Complete");
if (response.trim() === "" || response.toLowerCase().indexOf("error") > -1) {
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text(response.trim());
} else {
var $target =
$(this).parents("form").find(".filelist.queue").find("li[data-index=" + file.index + "]");
$target.find(".file").text(file.name);
$target.find(".progress").remove();
$target.find(".cancel").remove();
$target.appendTo($(this).parents("form").find(".filelist.complete"));
}
}
function onFileError(e, file, error) {
console.log("File Error");
$(this).parents("form").find(".filelist.queue")
.find("li[data-index=" + file.index + "]").addClass("error")
.find(".progress").text("Error: " + error);
}
HTML where i used formstone control
<div class="uploadImage" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadImage","chunked":true}'></div>
<div class="uploadDocs" style="height:100px;border:1px dashed #000;" data-upload-options='{"action":"<?php echo base_url();?>innovation/uploadDocs","chunked":true}'></div>
Try this...
.ajax({
type: 'POST',
url: base_url + 'innovation/addProcess',
dataType: "html",
data: $('#add_innovation').serialize(),
success: function(result) {
var res = result.split("#");
if (res[0] == 'success') {
$(".uploadImage").upload("defaults", {postData: {"ideaId":10}});
$(".uploadImage").upload("start");
$(".uploadDocs").upload("defaults", {postData: {"ideaId":10}});
$(".uploadDocs").upload("start");
} else {
showNotification('alert-danger', result);
}
},
error: function(error) {
console.log('error');
}
});
Before you call the method "start" you need to add the option "postData". As what I understand from the documentation the "start" method doesn't allow additional params.
CodyKL's solution works using the defaults method, or you can append extra params with the beforeSend callback:
// Var to store ID of inserted item
var resultId;
// Insertion AJAX
$.ajax({
...
success: function(result) {
// Get the id from the result
resultId = result;
// Start the upload
$(".uploadImage").upload("start");
},
...
});
// Initialize Upload
$(".uploadImage").upload({
...
beforeSend: onBeforeSend,
...
});
// Modify upload form data
function onBeforeSend(formData, file) {
formData.append('ideaId', resultId); // add resultID obtained in insertion AJAX above to form data
return formData; // Return modified formData
}
You should read up on how JS and the FormData API work: https://developer.mozilla.org/en-US/docs/Web/API/FormData.

submit form to a php file with angular

i would like to submit my form to a php file
var myApp = angular.module('myApp',[]);
myApp.controller('FormController', function($scope, $http) {
$scope.task = {
group: 'fix',
showme: true,
select1: 'basique',
select2: 'micro',
select3: '1',
select4: '1',
select5: 'jour'
};
var server = 'http://localhost/myserver.php?cd=add';
var parameters;
$scope.submit = function(form) {
angular.forEach($scope.task, function(value, key) {
if(value) {
if(key === 'date') {
value = new Date(value).getTime();
}
parameters += '&'+key+'='+value;
}
});
console.log(server+parameters);
//$http.post(server+parameters)
//.success(function(result) {
// console.log("success", result);
//})
//.catch(function(error) {
// console.log("error", error);
//})
}
})
this is the codpen codepen
is this valid?
the result at should be http://localhost/myserver.php?cd=add'name='&'describe='
You are create query string using foreach() and pass with server url but. you are use $http.post(). you have to use $http.get() if you want pass with server url.
Below example with help
$scope.submitForm = function($valid)
{
myobject = {'email' : $scope.user.email, 'pass' : $scope.user.pass};
Object.toparams = function ObjecttoParams(obj)
{
var p =[];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: WSURL + '/login',
method: "POST",
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config)
{
}
}).error(function (data, status, headers, config)
{
});
}

Categories