500 Internal server error also after checking CSRF protection - laravel

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.

Related

ajax Cannot POST /index.html cordova

<script>
$.ajax({
url: "http://localhost/app/connexion.php",
type: "POST",
dataType: "json",
/*contentType: 'application/json',
data: '{ email: "hajjajihajer24#gmail.com", password : "00000" }',*/
data: $("#connexionForm").serialize(),
success: function(msg){
if(msg == "1") {
$("#status").text("Login Success..!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + jqXHR.responseText);
}
});
<form action=""class="sign-in-form" method="POST" id="connexionForm" name="connexionForm">
<h2 class="title"> S'indetifier </h2>
<div class="input-field">
<i class="fas fa-user"></i>
<input type="text" placeholder="Nom Utilisateur" name="email" id="email"/>
</div>
<div class="input-field">
<i class="fas fa-lock"></i>
<input type="password" placeholder="Mote de passe" id="password" name="password" />
</div>
<p id="status"></p>
<input type="submit" value="Login" class="btn solid" id="loginButton" onclick="ValidateEmail(document.connexionForm.login)" />
</form>
I'm building a Cordova APP with simple REST calls.
The issue is when I make a AJAX with POST, Chrome sends me: "XMLHttpRequest cannot load http://localhost/app/connexion. Response for preflight has invalid HTTP status code 405" on console.
and return Cannot POST /index.html
But, if I make a AJAX call with GET (basically return an value from database) the things works like a charm.

i am using ajax but it show method not support i check but method is same in ajax and in route

I am trying this but it show me this
The POST method is not supported for this route. Supported methods: GET, HEAD.
Route
'''
Route::get('/','EmployeeController#index');
Route::post('employee.store','EmployeeController#store')->name('employee.store');
'''
Ajax
'''
$(document).ready(function(){
$('#insert_form').on('submit',function(e){
event.preventDefault();
$.ajax
({
type:"POST",
url:"{{route('employee.store')}}",
data:new FormData(this),
dataType: 'json',
success: function(data)
{
alert();
window.location.reload();
}
});
});
})
'''
blade
'''
<form action="" id="insert_form" method="post">
#csrf
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="email" class="form-control" name="email" placeholder="Email Address">
</div>
</div>
</form>
'''
Pls modify your POST route:
// Routes should not contains dots.
Route::post('/employees','EmployeeController#store')->name('employee.store');

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
}
})

Laravel - How to capture Ajax Request Payload Data?

Not a Duplicate Question!!!
Here is my code, using Laravel 5.4.
Form in .blade.php file:
<form id="read-data-form" name="form" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="comCode" id="comCode" type="hidden" value=""/>
<label><span class="text-danger">*</span> Upload File :</label>
<input name="file" id="fileToUpload" type="file" accept="text/*" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6 ">
<div class="text-right">
<button type="submit" class="btn operations-btn btn-default" id="upload">Upload</button>
<button type="button" class="btn operations-btn btn-default" id="stop">Stop</button>
</div>
</div>
</div>
</form>
Ajax-request in .js file:
$("form #read-data-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var promise = $.ajax({
url: 'read_data/file/check',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
encode: true
});
promise.done(function(response){
});
promise.fail(function(error){
});
promise.always(function(){
});
}
Browser Console > Network > Headers > Request Payload:
Route in web.php file:
Route::post('read_data/file/check', 'ReadDataController#checkFile');
checkFile() method in ReadDataController.php file:
public function checkFile(Request $request)
{
$comCode = trim($request->comCode);
$file = $request->file('file');
dd($file);
}
Browser Console > Network > Preview > Request Payload:
This is how output of dd().
Issue:
File could not be captured as in a normal 'multipart/form-data' form without ajax request.
OK. Finally, I have a solution which is given by a senior person.
Removed this code:
$file = $request->file('file');
Added the following codes:
$uploadDirPath = 'C:/uploaded_files/';
$uploadFile = "moved_uploded_file.txt";
$request->file('file')->move($uploadDirPath, $uploadFile);
$uploaded_file = $uploadDirPath.$uploadFile;

submitting a form in a modal with ajax using laravel

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
});

Resources