Reputation: 29
I'm having a problem getting my AJAX to work. I've looked around but I can't seem to find anything that helps with how I've structured my code.
Right now the data fields input into the database fine, however I want to also add a file upload (profile picture) but when I look into the networking tab it doesn't appear within the form data. I'm not too worried about the controller itself for the moment, but how do I get the AJAX request to send the file to the controller?
If anybody knows how I can fix this I'd really appreciate it.
Thanks!
AccountController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class AccountController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
return view('Account.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$this->validate($request, [
'name' => '',
'email' => '',
'telephone' => '',
'job_title' => '',
'profile_description' => '',
'education' => '',
]);
User::find(Auth::user()->id)->update([
'name' => $request->get('name'),
'email' => $request->get('email'),
'telephone' => $request->get('telephone'),
'job_title' => $request->get('job_title'),
'profile_picture' => $request->get('profile_picture'),
'profile_description' => $request->get('profile_description'),
'education' => $request->get('education'),
]);
$userImage = User::find(Auth::user()->id);
if (!empty($request->file('profile_picture')) && $request->file('profile_picture')->isValid()) {
$fileName = md5(time() . pathinfo($request->file('profile_picture')->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . pathinfo($request->file('profile_picture')->getClientOriginalName(), PATHINFO_EXTENSION);
$request->file('profile_picture')->move('profile-pictures', $fileName);
$userImage->update([
'profile_picture' => $fileName,
]);
} else {
$fileName = $request->get('old-image');
}
$userImage->update([
'profile_picture' => $fileName,
]);
}
Form
<form class="form-horizontal" id="account-update" role="form" method="POST" action="{{ url('account.update', auth()->user()->id) }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="telephone" class="col-sm-2 control-label">Contact Number</label>
<div class="col-sm-10">
<input name="telephone" type="telephone" class="form-control" id="telephone" placeholder="+(44)754 5635 950">
</div>
</div>
<div class="form-group">
<label for="job_title" class="col-sm-2 control-label">Job Description</label>
<div class="col-sm-10">
<input name="job_title" type="text" class="form-control" id="job_title" placeholder="Web Developer">
</div>
</div>
<div class="form-group">
<label for="profile_description" class="col-sm-2 control-label">About Me</label>
<div class="col-sm-10">
<textarea name="profile_description" class="form-control" id="profile_description" placeholder="Tell us about yourself..."></textarea>
</div>
</div>
<div class="form-group">
<label for="education" class="col-sm-2 control-label">Education</label>
<div class="col-sm-10">
<input name="education" type="text" class="form-control" id="education">
</div>
</div>
<div class="form-group">
<label for="profile_picture" class="col-sm-2 control-label">Profile Picture</label>
<div class="col-sm-10">
<input name="profile_picture" type="file" class="form-control" id="profile_picture">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn send-btn">Submit</button>
</div>
</div>
</form>
AJAX
<script>
$(document).ready(function(){
$('#account-update').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '{{ route('account.update', auth()->user()->id) }}',
enctype: 'multipart/form-data',
method: "PUT",
data: {
'name':$('input[name=name]').val(),
'email':$('input[name=email]').val(),
'telephone':$('input[name=telephone]').val(),
'job_title':$('input[name=job_title]').val(),
'profile_description':$('textarea[name=profile_description]').val(),
'education':$('input[name=education]').val(),
'profile_picture': $('file[name=profile_picture]').val(),
'_token': $('input[name=_token]').val()
},
success: function(data){
console.log(data);
}
});
return false;
});
});
</script>
Upvotes: 1
Views: 2372
Reputation: 14027
Try FormData.
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data.
$('#account-update').on('submit', function(e) {
e.preventDefault();
var formData = new FormData();
// other inputs
formData.append("userfile", $('file[name=profile_picture]').files[0]);
//append some non-form data also
formData.append('name',$('input[name=name]').val()),
$.ajax({
type: "POST",
url: postDataUrl,
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(data, textStatus, jqXHR) {
//process data
},
error: function(data, textStatus, jqXHR) {
//process error msg
},
});
Upvotes: 1