Phoebe
Phoebe

Reputation: 27

Ajax/jQuery to use array to populate table in 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>

Upvotes: 1

Views: 1187

Answers (2)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

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

}
});

Upvotes: 2

Michael Hurley
Michael Hurley

Reputation: 369

Do you know if Route::get('/search', 'FrontendWidgets\PolicyWordingController@search'); returns JSON?

Upvotes: 1

Related Questions