Hello I'm trying to make a button that once clicked I save the information written in the text field plus the current user logged in ID. Once clicked just refresh the page (or just do nothing) and save that information in the database.
But my button is doing nothing...
My Controller:
public function addSchool(Request $request){
DB :: table("schools") -> insertGetId
(
array("id_professor" => Auth::id(), "escola"=> $request->input('escola'),
)
);
return redirect('/teacher');
}
My zone where i have the textfield and button:
<div class="form-group">
<h3 style="color: #000000" for="escola">Nome da Escola</h3>
<input type="text" id="escola" name="escola" class="form-control">
</div>
<div
<button type="submit" class="btn btn-danger">Registar Escola</button>
</div>
I didn't add any web.php (routes file) here because i don't want it to go any page.
These are my Database Columns
CodePudding user response:
You cant save using a method without a route with only PHP. If you want to do this, take a look on livewire component, who allow you to use Javascript with PHP. But you need to few understand Javascript. I propose you to create a route with a name and just point it to the method
Here in web.php
Route::post('/post-form', [YourController::class, 'addSchool'])->name('addschool');
Then after in your view
<form action="{{route('addschool')}}" method="post">
@csrf
<div class="form-group">
<h3 style="color: #000000" for="escola">Nome da Escola</h3>
<input type="text" id="escola" name="escola" class="form-control"/>
</div>
<div>
<button type="submit" class="btn btn-danger">Registar Escola</button>
</div>
</form>
CodePudding user response:
You can do that by using ajax call from the front-end using on click event attach to button. it will dynamically send the request to your specified controller method and you can display the response(data) in the front-end specified place without page loading
for example take a look at the given code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e){
e.preventDefault();
var escola = $("input[name=escola]").val();
$.ajax({
type:'POST',
url:'{{route('addschool')}}',
data:{name:escola},
success:function(data){
alert(data.success);
//add your login here for the response
}
});
});