I want to load a page content (search.blade.php
) inside a specific div element after form submit for the controller function using AJAX in Laravel blade.
The data must be sent to the (search.blade.php
) page from the controller.
My Form:
<form data-action="{{ route('viewsearch') }}" method="POST" enctype="multipart/form-data" id="searchview">
@csrf
<input type="text" name="email" class="form-control" placeholder="Username/Email" style="width:180px; float:left; font-size:12px;">
<select name="cate" class="form-control" style="width:180px; float:left; font-size:12px;">
<option value="">Select Category</option>
<option value="Programmer">Programmer</option>
<option value="Software Engineering">Software Engineering</option>
</select>
<button type="submit" class="btn btn-primary" style="width:180px; float:left; background-color:green; font-size:12px;">Search Professional</button>
</form>
Div where to show content from another page:
<div id="dataview">
@include('htmlview')
</div>
Ajax & JavaScript for the form submit and load content of search.blade.php
page in the specific div:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var form = '#searchview';
$(form).on('submit', function (event) {
event.preventDefault();
var url = $(this).attr('data-action');
$.ajax({
url: url,
method: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (response) {
$("#dataview").html(response)
},
error: function (response) {
}
});
});
});
</script>
Web route:
Route::post('viewsearch', [App\Http\Controllers\Controller::class, 'viewsearch'])->name('viewsearch');
Controller function for receive data from the form, send data to the search.blade.php
page:
public function viewsearch(Request $request)
{
$user = $request->email;
$cate = $request->cate;
return view('search',['user'=>$user,'cate'=>$cate]);
}