submitting a form in a modal with ajax using laravel - ajax

I'm trying to upload both text and files through a form loaded inside a modal and submit it using ajax (I'm using Laravel 5.2) and I can't figure out why it doesn’t working. I have tried many solutions found here and through a search engine.
A simple form (this form is loaded in a modal)
<form id="registerForm" enctype="multipart/form-data" class="form-horizontal" role="form" method="POST">
<div class="form-group">
<label class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="name" id="name">
<div class="form-group">
<label class="control-label col-md-4" for="pwd">Choose File</label>
<div class="col-md-6">
<input type="file" class="form-control" id="fileProfPic" name="prof_pic">
</div>
</div>
<button type="submit" id="registerButtonModal" class="btn btn-primary"><i class="fa fa-btn fa-user"></i>Register</button>
</form>
.js
$("#registerButtonModal").click(function(){
$('#registerForm').submit(function (e) {
e.preventDefault();
var formData = new FormData($('#registerForm')[0]);
$.ajax({
url: 'register',
type: 'POST',
data: formData,
success: function(msg){
alert(msg);
}
contentType: false,
processData: false
});
});
});
route
Route::post('register',[
'uses' => 'AdminController#postRegister',
'as' => 'postRegister']);
controller //just trying to make it work
public function postRegister(Request $request)
{
return "success";
}

Your problem is likely due to the fact your AJAX should be returning a JSON response with your controller.
Try the following:
public function postRegister(Request $request)
{
return response()->json(['success' => 'success']);
}
With the above you will now have access to the object within your view.
Also, remember to pass your CSRF token in your AJAX. I usually add this in my view when i use AJAX and I pass that variable to data as seen below:
<script>
var token = '{{ Session::token() }}';
</script>
$.ajax({
url: 'register',
type: 'POST',
data: {variable1: variable1, variable2: variable2, _token: token},,
success: function(msg){
alert(msg);
}
contentType: false,
processData: false
});

Related

My ajax request return status error 405 on laravel

I'm using laravel 6. IT returns me error 405 when using external ajax.js file to handle my form.
message: The POST method is not supported for this route. Supported methods: GET, HEAD.
This is my form in blade:
<form >
#csrf
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name" required="">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<strong>Email:</strong>
<input type="email" name="email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
my ajax.js:
$(document).on('submit','#employeeSignupFrom',function (e) {
var token = $('input[name="_token"]').attr('value')
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
$url:'/signupemployee',
type:'post',
data: $(this).serialize(),
contentType:'json',
success: function( response, textStatus, jQxhr ){
alert('done')
},
error: function( jqXhr, textStatus, errorThrown ){
alert('error!');
}
});
e.preventDefault()
})
the route(web.php):
Route::post('/signupemployee','FormsController#signupEmployee');
and my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class FormsControllers extends Controller
{
public function signupEmployee(Request $request){
$employeeInfo=$request->all();
return response()->json(['alert'=>'done!']);
}
}
First remove $ sign from your url:
//$url:'/signupemployee', <- remove $
url:'/signupemployee',
Second change contentType to:
contentType: 'application/json',
Finally your ajax should be something like this:
$.ajax({
url: '/signupemployee', //<- $ sign should deleted
type: 'POST',
data: data,
contentType: 'application/json', //<- not just json
headers: {
'X-CSRF-TOKEN': token
}
})

Cannot read multipart/form-data from request in Laravel

I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!

500 Internal server error also after checking CSRF protection

I'm still having problems with submitting a form via AJAX in a Laravel project. I tried following some tutorials about submitting tokens with an AJAX request in Laravel, but I'm still having the error 500 (internal server error)
This is my script
$(document).on('click',"#registra_fornitore",function() {
$.ajax({
url: '/fornitori/create',
method: "POST",
data: {
'name':$('#nameSF').val(),
'_token': $('#_tokenSF').val(),
'nit':$('#nitSF').val(),
},
dataType: "json",
success: function(data){
alert(data);
}
});
This is the HTML for the form
<form>
<div class="form-group">
<label for="nameSF">Nome</label>
<input type="text" class="form-control" id="nameSF" placeholder="Nome">
</div>
<div class="form-group">
<label for="nitSF">NIT</label>
<input type="text" class="form-control" id="nitSF" placeholder="NIT">
</div>
<input type="hidden" id="_tokenSF" value="{{ Session::token() }}">
<button type="button" class="btn btn-default" data-dismiss="modal">Annulla</button>
<button type="button" class="btn btn-primary" id="registra_fornitore">Registra</button></form>
And this is the routes file
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('home');
});
Route::get('insert/{scope}','AdminController#getInsert');
Route::post('fornitori/create','SupplierController#postCreate');});
Any ideas of the problem? I tried also the different approach, writing the token value in a meta tag in the header of my template, and passing it in the ajaxsetup
Sorry, I found out the problem was a misspelling error in the storing method in the controller.

laravel 5.1 formData - AJAX - PHP- Uploading multiple files

I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>

cannot upload file using ajax with formdata

I have the following code in my form.
I try to upload the files via ajax using jquery.
Other data fields in the form was submitted fine. But i cant add FILES to the POST request.
Here is my html code:
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="nimp" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Thumb Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="ntimp" id="ntimp" required>
</div>
</div>
My JQ Code:
$(document).ready(function(e) {
$('button.submit').click(function(e) {
e.preventDefault();
var a=new FormData();
alert(a);
$('.edit_form_prod_div').hide();
$.ajax({
type:"POST",
url:"ep.php",
data:a,
cahe: false,
processData:false,
contentType: false,
success: function(response){
$('.edit_prod_response').html(response)
},
error:function(response)
{ alert("Error Occures"); }
});
$('.edit_prod_response').show();
});
});
Try This Code
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function ()
{
$("#btnSubmit").click(function()
{
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "FileUploadHandler",
data: data,
processData: false, // Importent
contentType: false, // Importent
cache: false,
timeout: 600000,
success: function (data)
{ alert("File Uploaded...!")
}
});
});
</script>

Resources