You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中AJAX调用数据库取数失败,报'data is not defined'错误

Laravel AJAX获取数据报错"data is not defined"问题修复

问题描述

在Laravel框架中通过AJAX调用从数据库获取数据时,jQuery函数无法正常获取数据,且出现"data is not defined"错误,目标是展示数据库表中的所有数据。

相关代码

控制器代码

<?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);
        }
    }
}

AJAX函数代码

$(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);
    })
});

路由代码

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


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

Blade视图文件代码

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

错误提示

控制台报错"data is not defined",同时服务器端存在查询逻辑错误。


错误原因及修复方案

1. 控制器查询逻辑错误

  • 问题:使用DB::table('patients')->first()后链式调用where/orderBy/get(),first()返回单个模型实例而非查询构造器,导致后续方法调用失败,服务器返回500错误,前端无法获取有效JSON数据,从而触发"data is not defined"。
  • 修复:移除所有->first(),直接使用查询构造器:
// 搜索分支
$data = DB::table('patients')
    ->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();

// 默认分支
$data = DB::table('patients')
    ->orderBy('created_at', 'desc')
    ->get();

2. $output未初始化

  • 问题:直接使用$output .=拼接HTML,变量未提前声明导致服务器报错。
  • 修复:在处理数据前添加初始化代码:
$total_row = $data->count();
$output = ''; // 初始化变量
if($total_row > 0) {
    // ... 循环拼接代码
}

3. 返回数组错误

  • 问题:返回数组重复赋值table_data,且$table_data未定义,同时缺少AJAX所需的total_data字段。
  • 修复:修正返回数组结构:
$data = array(
    'table_data'   =>  $output,
    'total_data'   =>  $total_row // 对应前端的data.total_data
);

4. AJAX参数错误

  • 问题:jQuery AJAX的参数URL应为小写url,大写参数无法被识别;选择器$('total-patient-records')缺少ID选择符#。
  • 修复:
$.ajax({
    url:"/action", // 改为小写url
    method: 'GET',
    data: {query:query},
    dataType: 'json',
    success: function(data)
    {
        $('tbody').html(data.table_data);
        $('#total-patient-records').text(data.total_data); // 添加#
    }
})

5. 表格列数不匹配

  • 问题:控制器生成的表格行有9列,无数据提示的colspan="5"与实际列数不符,导致布局错乱。
  • 修复:修改colspan为9:
<tr>
    <td align="center" colspan="9"> 
        No Data Found
    </td>
</tr>

内容的提问来源于stack exchange,提问作者user19704437

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:25:18