Currently I am trying to pass a creation form to a controller. I have the route and the ajax call setup and talking to the route. My problem is that when I use the ajax call the inspect tool for headers is showing my form values correctly but when I go into the controller the request->input doesnt show any values for the form.
Here is my ajax call
$(document).on("click", ".form-submit-btn", function() {
// Get the form id.
var formID = $(this).closest("form").attr("id");
var serializedForm = $(this).closest("form").serialize();
var substringEnd = formID.indexOf("-form");
var route = formID.substr(0, substringEnd).replace("-", "_");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Submit the form.
$.ajax({
method: "POST",
url: "/" + route,
data: {
serializedForm
},
success: function(data) {
alert(data);
}
});
});
Here is my controller
// Create Role
public function create(Request $request)
{
// Get and validate request params
$role = $request->input('role_name');
$active = $request->input('role-active', false);
return $role;
}
And here is my route
Route::post('/create_role', 'RoleController#create');
Am I missing something that is preventing the ajax call from sending the values to the controller
Here is my form also if that helps.
<form id="create-role-form" class="form">
{{ csrf_field() }}
<button class="pull-right right-close-btn">X</button>
<h1>Add Role</h1>
<hr />
<div class="form-group">
<label>Role Name</label>
<input type="text" name="role_name" class="form-control" />
</div>
<div class="form-group">
<input type="checkbox" name="role_active" value="true" checked /> Active
</div>
<div class="form-group">
<button class="btn btn-primary form-control form-submit-btn">Create</button>
</div>
I think problem is this line
data: {serializedForm},
Just change it to
data: serializedForm,
and it should fix the problem.
Problems
I see two problems with your ajax request
Are you sure you're using ES-6 TransPiler because data:{serializedForm}, is ES-6 Syntax http://es6-features.org/#PropertyShorthand
If you're javascript is working fine. You should be able to get it like $request->get('serializedForm')['role_name'] with your existing code.
Hope it helps
Related
I am using Laravel with AJAX to send form update request. With other method such as POST request, everything works fine. I managed to do Update method as well but with a different method which is defining it on data field one by one. But since my new form has a lot of input field, I try to serialize it using FormData, but then the error of target class does not exist came out. The error in specific is
Target class [App\Http\Controllers\Form] does not exist
The Controller that I am trying to send to is named FormController, somehow from the error it removes the "Controller" part.
I am not sure what causes it, hope someone would enlighten me on this issue, thank you.
Laravel Blade
<form enctype="multipart/form-data" id="formUpdate">
#csrf
<input type="hidden" name="flowId" id="flowId" value="1">
<input type="hidden" name="formId" id="formId" value="{{ $formData->id }}">
#component('components.form.form-section-a', ['formData' => $formData, 'projectMember' => $projectMember])
#endcomponent
<div class="grid w-full">
<div class="sm:px-1 md:px-0">
<button class="border-green-600 bg-green-600 w-full py-2 rounded mt-3 text-white submitForm" type="submit">Update</button>
</div>
</div>
</form>
AJAX Script
$("#formUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
// dataType:'json',
processData: false,
success: function (response) {
console.log(response);
// return false;
},
});
});
in your button add data-url="route('Form')" or console.log(url); first then check
How should I handle the csrf_field() function when doing this with AJAX?
here is a link to the project repo.
Here is a link to the article which helped me write the code.
I'm pretty sure I don't have to make too many changes to the code to handle the forms with AJAX instead of regular blade.php form submissions, but I'm unsure of the implementation
<form id="add_item" method="POST" action="/item">
<div class="form-group">
<textarea name="item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" >Add Item</button>
</div>
{{ csrf_field() }}
</form>
you can also put csrf-token in header file like this...
<meta name="csrf-token" content="{{ csrf_token() }}">
then give one unique id to submit button... then after in JavaScript detect that click event. then after call ajax on click event of submit button
$.ajax({
type: "POST",
// url: "{{ route('admin.users')}}" + id,
// url : '/admin/users/',
url: "{{url('admin/users/')}}", // you can pass url using url() OR as simple url OR Route name also
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //get the Csrf token from header
},
data: { id: id, }, //pass here all data which you want to pass to controller
success: function (data) {
console.log(data);
}
});
get the csrf value using
var token = $('input[name="csrfToken"]').attr('value');
and append it to the header
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
you can read more about it here https://stackoverflow.com/a/51964045/9890762
SOLVED.
I had to remove the 'type' attribute from the form as ajax is being used instead,
and ensure the ajax functions are at /public/js/file.js
Then, to make the changes available to the folder resources
npm run dev
<form id="add_item_form" action="/item">
<div class="form-group">
<textarea id="add_item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button id="ajaxSubmit_add">Add Item</button>
</div>
</form>
This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)
I'm trying to make AJAX request with button in Laravel 5.5. Console returns me POST: 500 (Internal Server Error).
My Javascript code here:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#insertForm').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data: data,
dataType: 'json',
success:function(data)
{
console.log(data)
}
})
})
</script>
My HTML form code:
<form action="{{ URL::to('add') }}" class="translation-form" method="POST" id="insertForm">
<div class="language-area">
<textarea class="form-control wow fadeIn" data-wow-duration="0.5s" name="words" id="lang-input" rows="10"></textarea>
</div>
<p class="upload-info wow fadeInDown" data-wow-duration="0.5s" data-wow-delay="0.3s">
Add words from file
<input type="file" name="file-1" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple />
<label for="file-1"><span>"doc" or "docx"</span></label>
</p>
<div class="clearfix"></div>
<div class="text-center translate-option">
<button type="submit" class="btn btn-green btn-instant-translate wow fadeIn" data-wow-duration="0.5s">
Add
</button>
</div>
</form>
My AjaxController:
class AjaxController extends Controller
{
public function store(Request $request)
{
if($request->$ajax())
{
return "True request!";
}
}
}
And my route:
Route::post('/add', ['uses'=>'AjaxController#store', 'as'=>'ajaxAdd']);
Why does such an error occur? Ajax worked when I tried to just output the data in the console without usage requests to AjaxController.
the server responds with 500 because some exceptions are raised during the ajax call. i guess its because of the code in controller, the controller code should be like this
if($request->ajax())
{
return "True request!";
}
Edit: to respond to ajax request, you can use response objects and http response codes, instead of returning plain text, so that you can know the exact status of ajax call,
Doc link to laravel responses
Link to Http Response Codes
You got an rogue $ in $request->$ajax()
class AjaxController extends Controller
{
public function store(Request $request)
{
if($request->ajax())
{
return "True request!";
}
}
}
I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!
You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});
Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.
As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.