问题
I'm sorry. I have researched for several hours, several and I still do not reach success with this.
Let me explain:
I'm on the route /events/1
, so I'm already inside the details of the event.
When I select a date (that is why it is the variable "day_id") it makes a query. But each event has different days, that is why I need to pass the event ID also to make the query.
$event_id = "Dynamic Value";
$data = Hour::where('selected_date', $day_id)->where('event_id', $event_id)->get();
I don't know if I explain myself well, what I need to do is also that the ID is dynamic, like the day_id
.
I've been trying for more than 5 days in many ways.
I'm trying to get the ID of my "Event" via JavaScript and I want to send it as a variable to the controller but I have not been able to yet. Could anyone help me, please?
@section('scripts')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('change', '#day', function(){
var day_id=$(this).val();
var event_id = $('#event_id').val();
// console.log(day_id);
// console.log(event_id);
$.get('/hour?day_id=' + day_id, function(data){
$('#hours').empty();
$('#hours').append('<option value="0" disable selected="true"> Selecciona la hora</option>');
for (var i = 0; i < data.length; i++) {
currentDay = data[i].hour;
console.log(currentDay);
$('#hours').append('<option value="'+ data[i].hour +'">'+ data[i].hour +'</option>');
}
})
});
});
</script>
@endsection
With this code I'm getting the value of the date, but now I need to show the time depending on the ID of the event. That's why I need to pass the variable event_id
to the controller method. I'm using var event_id = $('#event_id').val();
This is the code in the Controller:
{
$day_id = Input::get('day_id');
$event_id = '2'; //I need this to be dynamic
$data = Hour::where('selected_date', $day_id)->where('event_id', $event_id)->get();
return response()->json($data);
}
Web.php
Route::get('/hour', 'Events\EventController@getHours')->name('ajax.hour');
Once again, I'm sorry. I have researched for several hours, several and I still do not reach success with this.
What I need is to know how to how to pass event_id
variable to laravel controller. Thanks!
回答1:
So, yes, you're getting the event ID here:
var event_id = $('#event_id').val();
But you're not doing anything with that variable. If you never use a variable you've assigned, that's a major indication that you have a problem in your code. Some programming languages will even refuse to compile because of it.
Pass the event ID in the query string of your GET request, just like you're doing with day ID:
$.get('/hour?day_id=' + day_id + '&event_id=' + event_id, function(data){
Then retrieve it the same way from the Input facade:
$event_id = Input::get('event_id');
来源:https://stackoverflow.com/questions/54391534/how-to-send-a-variable-from-js-to-my-laravel-controller