My ajax request return status error 405 on laravel - ajax

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

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.

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.

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

500 (Internal Server Error) For Ajax POST in Laravel

Please can someone provide a simple example for ajax in laravel 5.1. I have tried everything and still no success. Tried the other solutions here but no luck, maybe it is my copy of laravel, I really don't understand. I just want to see how its done correctly. Please help me out. Thanks.
Route: Route::post('/signin', 'UserController#ajax');
<form action="signin" method="POST" id="form1">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" value="{{ old('email') }}" onBlur="if(this.value=='')this.value='mail#address.com'" onFocus="if(this.value=='mail#address.com')this.value=''" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" name='password' value="password" onBlur="if(this.value=='')this.value='password'" onFocus="if(this.value=='password')this.value=''"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="submit" value="Login" name="submit" id="sign"></p>
</fieldset>
</form>
for the controller:
public function ajax(Request $request)
{
if(Request::ajax()) {
$data = Request::all();
print_r($data);
]);
}
And ajax:
$('#sign').click(function(event) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
var inputs = $('#form1').serialize();
$.ajax({
url: 'http://localhost/laravel/public/signin',
type: 'POST',
dataType: 'json',
data: inputs,
success: function (data) {
console.log(data);
}
})
return false;
});

Resources