Jack Perry Jack Perry - 2 months ago 12
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>
@endforeach
</select>
<br>
<label>Select a session:</label>
<br>
<select id = "sesh" name = "sesh">
<option value=""></option>
</select>
<br>
<label>Number of tickets:</label><br>
<select id = "count" name ="count">
@for ($i = 1; $i < 10; $i++)
<option value="{{$i}}">{{$i}}</option>
@endfor
</select>
<br><br>
<input type="submit" value="Submit">
{!!Form::close()!!}


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

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



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


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

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

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