0

I am trying to send a set of data including image file through ajax using formdata but when I want to access that data in laravel controller, it shows a blank array.

Here is my ajax code -

var fd = new FormData();
    fd.append("photo",files[0]);
    fd.append("user_id",localStorage.getItem('userId'));
    fd.append("doctype","dl_image");       
    console.log(fd);



   //ajax code
    $http.post('uploadfile', fd, {    
            withCredentials: true,      
            headers: { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') }       
     }).success(function(data, status) {        

               console.log(data);


     });

PHP code -

    $data = Request::all();
    $photo = Request::file('photo');
    $userid = Request::get('user_id');
    $doctype = Request::get('doctype');


    $postData = array(
        'photo' => $photo,
        'user_id' => $userid,
        'doctype' => $doctype  
    );
    var_dump($data);
    die();

When the data is dumped in browser's console, it shows

array(0) {
}

Need help.

1
  • Heads up, Angular 5+'s HttpClient sets the content type to FormData automatically if it detects a FormData() object being sent. Commented Jun 29, 2018 at 18:52

3 Answers 3

2

AngularJS sends POST requests with application/json type & JSON body by default.
So I think that you need to use:

headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},
data: $.param(data)

in ajax code.
You might need to use something like $name = Input::get('name'); instead of $userid = Request::get('user_id');

Sign up to request clarification or add additional context in comments.

1 Comment

Accept file? I didn't get you
1

When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined.

Try: headers: { 'Content-Type': undefined }

Comments

0

Please try serialize method of jquery.

function myForm( form ){
    var formData = $(form).serialize();
    att=form.attr("action") ;
    $.post(att, formData).done(function(data){
        alert(data);
    });
    return true;
}

1 Comment

I am using angularJs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.