Jack Perry Jack Perry - 10 months ago 50
Ajax Question

Laravel Routes with AJAX file

I'm new to Laravel and I'm trying to learn how to create a dynamic drop down box where the 2nd drop down box will change depending on what is selected in the 1st one.

Here is my form code inside my blade file:

{!! Form::open(array('url'=>'', 'files'=>true)) !!}
<label>Select a Cinema:</label><br>
<select id = "cinema" name = "cinema">
@foreach ($cinemas as $cinema)
<option value="{{$cinema->id}}">{{$cinema->name}}</option>
<label>Select a session:</label>
<select id = "sesh" name = "sesh">
<option value=""></option>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
@for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
<input type="submit" value="Submit">

Here is my AJAX code (also inside the blade file but in tags:

$('#cinema').on('change', function(e){
window.alert("On Change");
var cinema_id = e.target.value;

$.get('/ajax-subcat?cinema_id=' + cinema_id, function(data){
//success data
window.alert("On Success");
$.each(data, function(index, subcatObj){
$('#sesh').append('<option value=""' + subcatObj.id +'">'+subcatObj.name+'</option>');

And finally here is my route:

Route::get('/ajax-subcat', function(){
$cinema_id = Input::get('cinema_id');
$sessions = Session::where('cinema_id', '=', $cinema_id)->get();
return Response::json($sessions);

So this code is not generating any data and is instead giving me a 404 error.

I have verified that the AJAX code does go inside the "change" function, through alerts, however it is not showing the 2nd alert. In my limited understanding, I feel like there may be an issue in my routes file? As if the route file is returning data, the next function in AJAX should be running.

One thing I don't understand in the routes code is what Input::get('cinema_id') is doing. I think it's grabbing what the user input in the drop down box?

Thanks a lot for any help!

Answer Source

Since it's giving 404 error, I hope using full url will solve this. Use

$.get('{{ url('/ajax-subcat') }}?cinema_id=' + cinema_id, function(data){
    //success data