I work on a Laravel project and I tried to change the content of a div without refreshing the all page.
In my controller I created two functions like that :
public function index(){
$data = $this->client->fixtures()->getFixtures(['date' => date('Y-m-d')]);
return view('index')->with('details', $data);
}
public function getScores(Request $request){
$id = $request->id;
if($id == 'live'){
$liveScores = $this->client->fixtures()->getFixtures(['live' => 'all']);
}
if($id == 'all') {
$liveScores = $this->client->fixtures()->getFixtures(['date' => date('Y-m-d')]);
}
return response()->json([
'liveScores' => $liveScores
]);
}
I use the index()
to get the important live score at the beginning in the view like that :
@foreach($details['response'] as $detail)
<div class="kf_opponents_wrap2">
<div class="kf_opponents_wrap">
<p>{{$detail['league']['name']}}</p>
<div class="kf_opponents_dec">
....
</div>
@endforeach
Then I used the second function getScores
to get the json data during the Ajax call, so I used in that case a switcher button with two cases all
and live
:
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "GET",
url: urlToSend,
dataType:"json",
data: { id: clickedButton.val() },
success:function(response){
$(".kf_opponents_wrap2").html('');
var result = response.liveScores.response;
if (result.length > 0) {
Object.keys(result).map(k => {
$(".kf_opponents_wrap2").append('
<div class="kf_opponents_wrap">
<p>'+result[k].teams.home.name+'</p>
<div class="kf_opponents_dec">
.......
....
</div>
</div>'
);
});
}
});
}
$(document).ready(function(){
$("#text_onoff").on( 'click' ,function() {
$('#onoff').prop('checked' , $('#onoff').prop('checked') ? false : true).change();
});
$('#onoff').on('change', function(){
$(this).val(this.checked ? 'live' : 'all');
sendAjaxRequest($(this),'{{ route('getScores') }}');
});
});
The goal is that firstly get the important live score when page is started then when switching the button to live
for example then I got the new div content without refreshing, what I got is two divs and also when switching back to all
case finally the page stop working?