Home > Net >  Unable to fetch data from database using ajax function Laravel
Unable to fetch data from database using ajax function Laravel

Time:10-07

I am trying to fetch data from the database using ajax call, but my function in jquery is not working for fetching the data and I am getting an error "data is not defined". I don't know what goes wrong. I am trying to fetch all data from the database table and display it on the screen Here is my controller

<?php

namespace App\Http\Controllers;

use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;

class SearchPatient extends Controller
{
    
    function action(Request $request)
    {
        if ($request->ajax())
        {
            $query= $request->get('query');
            if ($query != '')
            {
                $data = DB::table('patients')->first()
                ->where('patientid','like','%'.$query.'%' )
                ->orWhere('fname','like','%'.$query.'%')
                ->orWhere('lname','like','%'.$query.'%')
                ->orWhere('contactno','like','%'.$query.'%')
                ->orWhere('gender','like','%'.$query.'%')
                ->orWhere('cnic','like','%'.$query.'%')
                ->orWhere('city','like','%'.$query.'%')
                ->orWhere('address','like','%'.$query.'%')
                ->get();
            }
            else
            {
                $data = DB::table('patients')->first()
                ->orderBy('created_at', 'desc')
                ->get();
            }
            $total_row = $data->count();
            if($total_row > 0)
            {
                foreach($data as $row)
                {
                    $output .= '
                    <tr>
                        <td>
                             '.$row->patientid.'
                        </td>

                        <td>
                        '.$row->fname.'
                        </td>


                        <td>
                        '.$row->lname.'
                        </td>


                        <td>
                        '.$row->cnic.'
                        </td>


                        <td>
                        '.$row->gender.'
                        </td>


                        <td>
                        '.$row->address.'
                        </td>


                        <td>
                        '.$row->contactno.'
                        </td>



                        <td>
                        '.$row->city.'
                        </td>


                        <td>
                        '.$row->created_at.'
                        </td>
                    
                    </tr>
                    ';
                }
            }
            else
            {
                $output='
                <tr>
                    <td align="center" colspan="5"> 
                    No Data Found
                    </td>
                </tr>';
            }
            $data = array(
                'table_data'   =>  $output,
                'table_data'   =>  $table_data
            );

            echo json_encode($data);
        }
    }
}


Here is my ajax function

$(document).ready(function() {


    fetch_patients('');

    function fetch_patients(query = '')
    {
        $.ajax({
            URL:"/action",
            method: 'GET',
            data: {query:query},
            dataType: 'json',
            success: function(data)
            {
                $('tbody').html(data.table_data);
                $('total-patient-records').text(data.total_data);

            }
        })
    }


    $(document).on('keyup', '#searchpatient', function(){
        var query = $(this).val();
        fetch_patients(query);
    })
});

Here is my route

Route::get('/action',  [SearchPatient::class, 'action'])->name('action');


Route:: get ('/SearchPatient',function(){
    return view ('SearchPatient');
});


Here is my blade file

<div >
    <h3 align="center">Search Patient</h3><BR>
        <div >
          <div >
            Search Patient Data
          </div>
          <div >
            <input type="text" name="searchpatient" id="searchpatient"  placeholder="Search Patient">           
          </div>
          <div >
            <h3 align="center">Total Data : <span id="total-patient-records"></span></h3>
            <table >
                <thead>
                    <tr>
                        <th>Patient ID</th>
                        <th>Name</th>
                        <th>CNIC</th>
                        <th>Gender</th>
                        <th>Address</th>
                        <th>Contact No</th>
                        <th>City</th>
                        <th>Last Visit</th>
                    </tr>
                </thead>


                <tbody>

                </tbody>
            </table>
          </div>
        </div>
        </div>
</div>



Error I am getting

CodePudding user response:

var url = '{{ route('get_products') }}';
var data = {
   "_token": $('input[name=_token]').val(),
          };
$.ajax({
 type: "get",
 url: url,
 data: data,
 success: function(response) {
        alert(response.data);            
  }
});




<------ controller ------>

public function get_products()
{
   $data =   DB::table('products)->get();
   return response()->json(['data' => $products]);
}

CodePudding user response:

You have error in your code, double key 'table_data' and undefined variable $table_data enter image description here

$data = array(
  'table_data'   =>  $output,
  'total_data'   =>  $total_row
);

return response()->json(['data' => $data]);

CodePudding user response:

enter image description here

here is the issue in the document-ready method the data variable is used but Never initialize before using it.

The solution in to pass fetch_patients('') an empty string in your method, instead of data (an undefined variable)

  • Related