Home > Software engineering >  getting empty input on form submit
getting empty input on form submit

Time:05-23

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 >
Search Student
<div >
    <div >
        <input id="studfnameSearch" name="studfnameSearch" type="text"   placeholder="student first name">            
        <div >
            <div >
                <button type="submit" >                    
                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

CodePudding user response:

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.

  • Related