I'm saving data with the help of ajax and laravel. In the form the text field data is saving but the file is not saving with the help of ajax.
This is my script.

<script>
    $(document).ready(function() {
    $('#ajax').submit(function(event){
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'post_contact',
            data: $('form#ajax').serialize(),
            dataType: 'json',
        })

        .done(function(data) {
            console.log(data); 
        });
        return false;
    });
});
    </script>

Dani AI

Generated

— the problem is that serializing a form with serialize() only sends text inputs; file inputs are not included. is right that you can use upload plugins for advanced features, but the simplest fix is to send the form as multipart data with FormData and have Laravel read the uploaded file on the server.

A minimal client-side approach (with jQuery) is to build a FormData from the form, include the CSRF token, and call $.ajax with processData: false and contentType: false so the browser sends a proper multipart request:

var form = document.getElementById('ajax');
var fd = new FormData(form);

// if you need to add the Laravel token manually:
// fd.append('_token', $('meta[name="csrf-token"]').attr('content'));

$.ajax({
  url: '/post_contact',
  type: 'POST',
  data: fd,
  processData: false,
  contentType: false,
  success: function(res){ console.log(res); },
  error: function(err){ console.log(err.responseText); }
});

On Laravel side, check for the file and store it safely. Example using the Request object:

public function postContact(Request $request)
{
    if (! $request->hasFile('attachment')) {
        return response()->json(['error' => 'No file uploaded'], 400);
    }

    $file = $request->file('attachment');

    if ($file->isValid()) {
        // store() uses configured filesystem; move() is an alternative
        $path = $file->store('uploads');
        return response()->json(['path' => $path], 200);
    }

    return response()->json(['error' => 'Upload failed'], 500);
}

Troubleshooting: ensure the file <input> has a name attribute that the server expects, confirm the CSRF token is sent, watch the Network tab to see multipart/form-data with a boundary, check php.ini settings (upload_max_filesize, post_max_size) and storage permissions, and use dd($request->allFiles()) or server logs to inspect incoming files. If you need client-side progress, chunking, or retries, consider a dedicated upload library as suggested by .

Recommended Answers

All 2 Replies

Member Avatar for Member #120589

Sending files via ajax is not this straightforward. You may need a 3rd party script like that from PLUpload or BlueImp.

Ok thankyou.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.