skip to Main Content

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 AppHttpControllers;

use HaruncpiLaravelIdGeneratorIdGenerator;
use IlluminateHttpRequest;
use AppHelpersHelper;
use IlluminateSupportFacadesDB;
use AppUser;
use AppModelspatient;
use IlluminateSupportFacadesValidator;

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 class="container box">
    <h3 align="center">Search Patient</h3><BR>
        <div class="panel panel-default">
          <div class="panel-heading">
            Search Patient Data
          </div>
          <div class="panel-body">
            <input type="text" name="searchpatient" id="searchpatient" class="form-control" placeholder="Search Patient">           
          </div>
          <div class="table-responsive">
            <h3 align="center">Total Data : <span id="total-patient-records"></span></h3>
            <table class="table table-striped table-bordered">
                <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

3

Answers


  1. 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)

    Login or Signup to reply.
  2. 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]);
    }
    
    Login or Signup to reply.
  3. You have error in your code, double key 'table_data' and undefined variable $table_data
    enter image description here

    //Jquery
    var data = {
        "_token": $('input[name=_token]').val(),
        query:query
    };
    $.ajax({
            URL:"/action",
            method: 'GET',
            data: data,
            dataType: 'json',
            success: function(data)
            {
               $('tbody').html(data.table_data);
               $('total-patient-records').text(data.total_data);
            }
    })
    
    //controller
    
    $data = array(
      'table_data'   =>  $output,
      'total_data'   =>  $total_row
    );
    
    return response()->json(['data' => $data]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search