Select Box OnChange Ajax Request via Laravel Controller Part-2

Send Ajax GET Request on-change of select-box and handle it via Laravel Controller Part-2

Well in this Article we will use the dataType as json. If you haven’t read my last article, do read that first and then continue reading this one; here’s the link.

Just to recap, We have two database tables “Company” and “Packages” and they are in One-to-Many Relationship. We want to populate Packages of a Company on selection of a Company from Select-box via Ajax GET call. We have seen it working perfectly in the last article where we’ve used ajax dataType as html but this time we’ll be using json.

Way #2: dataType – JSON

On changing dataType to json, we’ve quite a leverage, as we can get both outputs i.e. as HTML and JSON as well. That’s the beauty of JSON, let me show you how!

Goto the “getpackages method”, this is what we have from the previous article:

public function getpackages($id)
 {
 $html = '';

$company = Company::findOrFail($id);
 $packages = $company->packages;

// Send as HTML

$html .= '<select id="remove_select" name="packages" class="form-control">';
 $html .= '<option> --- </option>';
 foreach ($packages as $package)
 {
 $html .= '<option value="'.$package->uid.'"> '.$package->uid.'. '.$package->package_name.' </option>';
 }
 $html .= '</select>';

return $html;

}

Now I’ll just extend this method a bit:

public function getpackages($id)
 {
 $html = '';

$company = Company::findOrFail($id);
 $packages = $company->packages;

// Send as HTML

$html .= '<select id="remove_select" name="packages" class="form-control">';
 $html .= '<option> --- </option>';
 foreach ($packages as $package)
 {
 $html .= '<option value="'.$package->uid.'"> '.$package->uid.'. '.$package->package_name.' </option>';
 }
 $html .= '</select>';

//return $html;

// SEND as JSON
 $packages2 = $company->packages->lists('package_name','id');

// return $packages;

return ( array( $html, $packages2 ) );

}

Here, I’ve just edited+added last 5 lines in the getpackages method. See that I’ve commented the “return $html” line and created another variable named “$packages2” where we are selecting only two fields rather than the whole object: “package_name” and its respective “id” via using Laravel’s LIST method. And in the last, we are returning an array having both the variables. This is what makes json beautiful!

Now how to use these two variables in our ajax? Its simple.. but first let me just tell you that I’ve created another div col-3 for populating the JSON data and give “id = package_div_json”. [see image and code below]

select-box-onchange-ajax-laravel-controller-5

 

<div class="col-xs-3">
 <label>Select a Package (as JSON/jQuery)</label>
 <div id="package_div_json">
 </div>
 </div>

 

Whereas, Our Route will remains the same:

Route::get('getpackages/{val}', 'GroupController@getpackages');

 

Now back to our Ajax, this is what we have in Part-1:

<script>
 $('#company').change(function(e)
 {
 e.preventDefault();
 $y = $(this).val();
 // alert($y);

$("select").remove( "#remove_select" );

$.ajax
 ({
 url: '{{ url('getpackages') }}/'+$y,
 type: 'GET',
 dataType: 'json',
 success: function(data)
 {
 console.log(data);

//HTML
 //$("#package_div_html").append(data);

}
 });
 });
 </script>

In the above script, I’ve updated few lines and marked those line in bold. First I’ve changed the dataType to json and added console.log to show you guys the data we are retrieving from the server and commented the append data line because it won’t work as we’ve an array of data now. Let just see what we are getting in our console first. [see image below]

select-box-onchange-ajax-laravel-controller-6

So we are getting the expected output from the server. Now we just have to populate them both in their respective divs. For that, update your script:

<script>
 $('#company').change(function(e)
 {
 e.preventDefault();
 $y = $(this).val();
 // alert($y);

$("select").remove( "#remove_select" );

$.ajax
 ({
 url: '{{ url('getpackages') }}/'+$y,
 type: 'GET',
 dataType: 'json',
 success: function(data)
 {
 // console.log(data);

//HTML
 $("#package_div_html").append(data[0]);

//JSON / jQuery
 $jsonhtml = '';
  $jsonhtml = $jsonhtml + '<select id="remove_select" name="packages" class="form-control">';
  $jsonhtml = $jsonhtml + '<option> --- </option>';
  $.each(data[1], function (index, value)
  {
  $jsonhtml = $jsonhtml + '<option value="'+index+'">'+index+'. '+value+'</option>';
  });
  $jsonhtml = $jsonhtml + '</select>';
  $("#package_div_json").append($jsonhtml);
 }
 });
 });
 </script>

Again I’ve marked the changes as bold. First I’ve comment out the console.log then un-comment the append html line. Note that now I’ve written data[0] in append function pointing that I’m using the first item in the data array which was the $html variable (HTML).

And after that I somehow do the exact same thing but now using jQuery. Using data[1] in each function and storing the html in $jsonhtml variable and appending it into the “package_div_json” div.

Lets now demonstrate how everything is working in the browser. [see images below]

select-box-onchange-ajax-laravel-controller-7

select-box-onchange-ajax-laravel-controller-8

I hope you like both of my articles. You ask questions via comments. Do point out any mistakes (if any). Don’t forget to share it. Thanks! 😉

One thought on “Select Box OnChange Ajax Request via Laravel Controller Part-2

Leave a Reply

Your email address will not be published. Required fields are marked *