Search code examples
phpjqueryajaxlaravellaravel-9

getting empty input on form submit


I am trying to implement a search function, currently, I am implementing a single search field but there will be more in future.

The problem is when I submit the form to search the data it is submitting a null value as I can see in the result query. and console.log() also printing else block even if I have input in the input field. what is the issue, everything looks fine to me, anyone can point out the issue please?

blade

<form id="studSearchForm" autocomplete="off" method="GET" enctype="multipart/form-data">
@csrf
<div class="searchBox">
Search Student
<div class="searchContainer">
    <div class="input-group">
        <input id="studfnameSearch" name="studfnameSearch" type="text" class="form-control"  placeholder="student first name">            
        <div class="input-group-append">
            <div class="input-group">
                <button type="submit" class="btn btn-secondary">                    
                Search
                </button>
            </div>
        </div>
    </div>
</div>
<script>
    $("#studSearchForm").submit(function(e) {
    e.preventDefault();
    const fd = new FormData(this);
    var _url = '{{ route('student.fetch.route') }}';
    $.ajax({
        url: _url,
        method: 'GET',
        data: fd,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function(response) {
            console.log(response);            
        }
    });
});    
</script>

web route

Route::get('student-fetch', [StudentRegController::class, 'fetchStudent'])->name('student.fetch.route');

controller

public function fetchStudent(Request $request) {
    $fnameQuery = $request->input('studfnameSearch');    
    if (!empty($fnameQuery)) {
        $studSearch = DB::table('school_students')->where('student_first_name', 'LIKE', "%{$fnameQuery}%")
            ->get('student_first_name');
        return response()->json($studSearch);
    } else {
        return response()->json("empty search");

    }
}

screenshot


Solution

  • FormData is used to generate multipart form data request bodies.

    It isn’t compatible with a GET request, which can’t have a request body and expects data to be placed in the query string.

    Normally I would suggest using URLSearchParams to generate a query string, but I don’t know if jQuery is modern enough to support it. Consider jQuery serialize instead.