1

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

17
  • There's a lot of parts here where it could go wrong. Open up your browser's developer console, and check the Console tab when you run the query. Are there any errors there? Check the Network tab, and click on the request that's made. Are you getting a proper response? Commented Oct 6, 2022 at 12:17
  • can you show me the Error response as a Screen short? Commented Oct 6, 2022 at 12:18
  • @UmerRasheed I have attached the error ss. Commented Oct 6, 2022 at 12:45
  • @aynber no, I am not getting any response in the network tab however I am getting errors in the console and I have attached that image in edited code. Commented Oct 6, 2022 at 12:47
  • Where is data coming from in fetch_patients(data);? You're calling the function as soon as the document loads and passing a parameter that does not appear to have been defined. Commented Oct 6, 2022 at 12:48

3 Answers 3

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

1
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]);
}

8 Comments

In this way, create a clean ajax action and check it out.
kindly use my code if you can debug it as I am not getting any errors but also not fetching the data as the document loads.
dd(); Check your controller part by using it, but the problem seems to be in ajax. First of all, use the empty ajax that I have presented to you in the example and check whether the data is coming. then include your own code in your controller.
"message": "Undefined variable: output" this is the error I got in the controller
Return response.data with for and print the values ​​one by one.
|
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)

4 Comments

I know that but what's the solution?
check answer again.
still not fetching the data
then this is an issue within your method ... about the data is undefined you have resolved that... please take a look or add a debugger, where the method is doing something else than expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.