1

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

2

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

}
});
Sign up to request clarification or add additional context in comments.

11 Comments

Ah okay, sorry jquery isn't my speciality, how would I go about doing this?
^ One more fix. You are using the POST method in your jQuery but the route is expecting a GET request.
I have edited my answer. Keep in mind that you cannot pick up the values from html the way you have added it in your javascript/jQuery code. Read about selectors in javascript and jQuery. Also, you need to determine from what elements you want to pick values, since I am not sure if you want to pick it up from <td> elements
@B_CooperA, I noticed that, thanks, I have corrected it directly on user's question
I've updated my code, and now all it seems to be returning is a blank page?
|
1

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

2 Comments

Currently it's just an array

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.