Nov 30th, 2021 at 03:30 PM
Laravel 8 JQuery ajax form submit
form.blade.php
<?php
$action=url("postform");
echo "<form action='$action' method='post'>";
echo "<input type='hidden' name='_token' value=".csrf_token()." />";
echo "Name: <input type='text' name='txtName' id='txtName' />";
echo "<input type='submit' name='btnSubmit' id='btnSubmit' />";
echo "</form>";
?>
<div id="output"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
$("#btnSubmit").on("click",function(e){
e.preventDefault();
let name=$("#txtName").val();
let token=$("input[name='_token']").val();
$.ajax({
url: "<?php echo url("postform")?>",
//url: "{{route('abc')}}", // if name route is used
type:'POST',
data: {_token:token,txtName:name},
success: function(data) {
$("#output").html(data);
}
});
});
});
web.php
Route::get("testform",function(){
return view("postform");
});
Route::post("postform",[UserController::class,'postform'])->name('abc');
TestController.php
<?php
namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRedirect;
class UserController extends Controller
{
public function postform(Request $request,$id){
echo "Hi.. ".$request->txtName;
}
}
Comments 0