1

I'm using Laravel and in my controller I'm getting data from external API. So far I can successfully get the data and looping into select drop down.

Because of the large data I want to fetch this result only when a user clicks on a specific radio button, instead of every time when that page is loaded.

How can I fetch the data using AJAX?

Here's my code bellow:

Checkout Controller:

public function offices(Request $request) {

  $url = Http::get('the_url_of_the_api', [
    'userName' => '123456',
    'password' => '345678',

  ]);
  $response = json_decode($url);
  $offices = $response->offices; // this is the variable I get successfully and I loop in the code bellow

}

View

<select name="office" class="offices form-control">
  @foreach($offices as $office)
    <option value="{{ $office->name }}">{{ $office->name }}</option>
  @endforeach
</select>

Now I'm trying to get that data with AJAX, so I've created a route and Javascript bellow.

Route:

Route::get('/offices', 'App\Http\Controllers\CheckoutController@offices')->name('offices');

Javascript:

<script>
  $(document).ready(function(){

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('input[name="radio"]').click(function(){

      $.ajax({
        type: "GET",
        url: "/offices",
        data: '',
        success: function() {
            // How can I fetch that variable offices from the controller and loop inside the select drop down box? 
        }
      });
    });

  });
</script>
2
  • Your Route definition suggests a POST request, but you send a GET request from the javascript. Since nothing is changed, it's better to use GET here. Thus the route should be: Route::get(...). Furthermore, your question is about jQuery (and perhaps javascript). Not about php and Laravel. I suggest you remove those two tags. And finally a suggestion for your problem: try a console.log of the response you get in the success function. The jQuery doc will tell you more on how to include that response into the function. Commented Aug 20, 2021 at 11:19
  • yes, I missed to change back into GET in both places. I've removed the PHP tag but I'll keep Laravel tag as this is important issue with the Laravel subject Commented Aug 20, 2021 at 11:24

1 Answer 1

1

First I personally wouldn't use Ajax with Laravel, there are too many better alternatives, with my favorite being Laravel Livewire.

The problem with using AJAX is that you have to solve the fact that AJAX can't directly interact with Laravel's Blade Templates. I can think of two ways to deal with that issue.

OPTION 1: Return a JSON list of offices from your controller

Make your CheckoutController::offices() method returns the list of offices return offices; as JSON. This way your ajax method has the info you need to manipulate the dom. (This isn't tested, but something like this may work)

success: function(results) {
  let officeSelect = document.getElementsByName('office');
  let offices = results.data;
  for (var i = 0; i < offices.length; i++) {
    // BIND DATA TO <select> ELEMENT.
    officeSelect.innerHTML = officeSelect.innerHTML +
    '<option value="' + offices[i].name+ '">' + offices[i].name+ '</option>';            
  }
}

OPTION 2: Return the entire Blade view as html and insert it into the correct dom position. (again not tested)

Checkout Controller


public function offices(Request $request) {

  $url = Http::get('the_url_of_the_api', [
    'userName' => '123456',
    'password' => '345678',

  ]);
  $response = json_decode($url);
  $offices = $response->offices; 
  return view('offices', compact('offices')); // This view cannot extend another view.

}

Ajax Script

success: function(results) {
  document.getElementsByName('office-select-wrapper').innerhtml = results.data;    
}
Sign up to request clarification or add additional context in comments.

Comments

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.