<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.
Related
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
}
})
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;
From Postman, I am able to send a POST request to the server successfully as following:
Key Value
postinfo (file) info.json
data (file) data.csv
label (file) label.csv
Now I'm implementing this in HTML and JavaScript.
<div id="fileupload">
<form id="uploaddata" enctype="multipart/form-data">
<label for="file">Choose data file</label>
<input type="file" accept="file/csv">
<br>
<label for="file">Choose initial label file</label>
<input type="file">
<br>
<label for="file">Choose setting</label>
<input type="file">
<br>
<button type="submit">Next</button>
</form>
</div>
And JS:
$('#uploaddata').submit(function(e){
e.preventDefault();
var form = new FormData($("#uploaddata")[0]);
$.ajax({
url: albackend,
type:'POST',
data: form,
crossDomain: true,
processData: false,
contentType: false,
success:function(data){
console.log("success");
console.log(data);
$('#fileupload').hide();
$('#videoselect').show();
},
error: function (responseData, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
Data is not posted successfully yet, likely due to lacking of keys (postinfo, data, label). How could I solve this problem?
Your file inputs nave no name attributes, they need them to be the keys of the files in the request.
<div id="fileupload">
<form id="uploaddata" enctype="multipart/form-data">
<label for="file">Choose data file</label>
<input type="file" name="data" accept="file/csv">
<br>
<label for="file">Choose initial label file</label>
<input type="file" name= "label">
<br>
<label for="file">Choose setting</label>
<input type="file" name="postinfo">
<br>
<button type="submit">Next</button>
</form>
</div>
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!
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.