Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine image upload ajax with form submit ajax

I have image upload ajax like this

$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log(file);
    var uploadUrl = "/api/upload_image";//It will also goes to '/api/get_data'
    //fileUpload.uploadFileToUrl(file, uploadUrl);
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(e){
        console.log("Success");
    })
    .error(function(e){
        console.log("Error");
    });
};

And calling submit form ajax like this.

$http({
    url: "/api/get_data",
    method: "POST",
    dataType:"json",
    data:JSON.stringify(this.formData)
}).success(function(data) {
    console.log("Success");      
}).error(function(error) {
    console.log("Error");
});

Both are working but separately, How to combine these two ajax into one, that is submit ajax, the second one.

Or is there any way to post image data in second ajax, I am using angular+laravel5.2

My file input in angular view is

<input type="file" file-model="myFile">

Thanks.

like image 812
Believe It or Not Avatar asked May 19 '16 05:05

Believe It or Not


1 Answers

You can combine this two ajax like this, to post image and formData, Try with this.

var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
fd.append('formData', JSON.stringify(this.formData));


$http({
    url: "/api/get_data",
    method: "POST",
    dataType:"json",
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined},
    data:fd
}).success(function(data) {

To retrieve formData you need to decode json at server side scripting.

like image 181
Drone Avatar answered Nov 06 '22 17:11

Drone