dongrong1856 2018-08-07 12:35
浏览 110

Ajax / jQuery使用数组来填充laravel中的表

So I have a search bar that is only for finding someone's policy, and so when they search their policy number, it gives them back some details including claims and policy wording. This all worked fine but worked as a redirect back to the same page just with the details added and so I wanted it to run with ajax so that the search all happens on one page. I have an array that I am passing to the blade, and now I want to show that information with ajax because currently it's in a hidden div, but it doesn't seem to be working?

Route:

Route::get('/widgets/policy-wording', 'FrontendWidgets\PolicyWordingController@policyWordingPage');
Route::any('/search', 'FrontendWidgets\PolicyWordingController@search'); 

Controller:

public function search(Request $request) {

if ($this->validate($request, [
    'ordernumber' => 'string|min:8|max:16',
], [
    'ordernumber.string' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
    'ordernumber.min' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
    'ordernumber.max' => ' Please enter a full order number. This will either be 8, 12 or 16 characters long and include a 2 letter prefix.',
]));

    try {
    $order = Order::findOrFail(decodeFullOrderNumber($request->ordernumber));
    } catch (ModelNotFoundException $exception) {
        return back()->withError('We could not find this policy number in our system, please try again')->withInput();
    }

      $description = $order->scheme->Description;
      $phonenumber = $order->scheme->ClaimsTelephone1;
      $policyurl = $order->scheme->PolicyURL;


      $policyinfo = array($description, $phonenumber, $policyurl);


     return response()->json([
            'status' => 'ok', 
            'policyinfo' => $policyinfo,
            'title' => "Policy Wording"
            ]);

}

Blade:

<form class="form-horizontal" role="form" id="policy-documents-search-form" action="/search">
    {{ csrf_field() }}
    <fieldset>

        <div class="form-group">
            <label for="username" class="col-sm-6 control-label">Enter your policy number</label>
            <div class="col-sm-8">
                <input type="text" name="ordernumber" id="ordernumber" class="form-control"/>
                <span class="text-danger">{{ $errors->first('ordernumber') }}</span>
            </div>
        </div>

            @if (session('error'))
                <div class="alert alert-danger">{{ session('error') }}</div>
            @endif

        <div class="form-group">
            <div class="col-sm-offset-4 col-sm-8">
                <button type="submit" class="btn btn-primary" id="search-button">Search</button>
            </div>
        </div>

         <div class="form-group" id="form-group" style="display:none;">
                <div class="container">
                @if(isset($policyinfo))
                <h2>Your Policy Details</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Claims Telephone</th>
                            <th>Policy Wording</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td id="name">{{ $policyinfo[0] }}</td>
                            <td id="phonenumber">{{ $policyinfo[1] }}</td>
                            <td id="policywording"><a href="{{ $policyinfo[2] }}">Policy Wording </a></td>
                        </tr>
                    </tbody>
                </table>
                @endif
            </div>


            </div>
        </div>


    </fieldset>
</form>

Script on blade:

<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="  crossorigin="anonymous">
</script>
<script>
 $.ajax({
 type: "POST",
 url: '{{ url('/search') }}',
 data: {
   rdernumber: $('#ordernumber').val()
  },
  dataType: 'JSON',
 success: function(response) {
 if(response.status == 'ok'){
    $("#form-group").show();
    $("#form-group").append("<td>" + response.policyinfo[0] + "</td>", "<td>" + response.policyinfo[1] + "</td>", "<td>" + response.policyinfo[2] + "</td>");
 }
 }
 });
  </script>
  • 写回答

2条回答 默认 最新

  • dounao4179 2018-08-07 12:38
    关注

    You need detect if request is ajax, and then to return response data in json format.

    In your search method, check if request is ajax with ajax(), or request expects json formatted response with method wantsJson():

     if ($request->ajax() || $request->wantsJson()) {
      //your code here
     }
    

    Response should be returned with response()->json() method

    return response()->json($response);
    

    or in your case:

    return response()->json([
    'status'=> 'ok', //in case you have errors, it is recommended to let know the frontend of your app whether status is ok or has an error 
    'policyinfo' => $policyinfo,
    ]);
    

    and that should be returned instead of your view() method return.

    In the frontend part, handle nodes of response in json format

    note I have fixed some typos and syntax errors, left some comments, but you need to fix a blade template to correspond to these comments and new code:

    $.ajax({
        type: "POST",
        url: '{{ url('/search') }}',
        data: {
            'Description': $('#policyinfo-0').val(), //I have corrected these, first you cannot have split wording for object keys, second, not sure from where you pick up the values, but you need to add some inputs with propert IDs
            'ClaimsTelephone': $('#policyinfo-1').val(),
            'PolicyWording': $('#policyinfo-2').val()
    },
    dataType: 'JSON',
        success: function(response) {
        if(response.status == 'ok'){
            $("#form-group").show();
    
            $("#form-group").append("<td>" + response.policyinfo[0] + "</td>", "<td>" + response.policyinfo[1] + "</td>", "<td>" + response.policyinfo[2] + "</td>");
        }
    
    }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料