jqueryajaxlaravel

JQuery and AJAX - Update div content using switch button


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() function 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].league.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 to get the important live score when page is started then when switching the button to live for example so I get the new div content without refreshing, what I got is two divs and also when switching back to all case the page stop working?


Solution

  • As per my understanding, on pageload you have got the "all" case data and once click on "live" then got the live score but againt change to "all" then your ajax code stops working...

    Please replace your change events of jQuery as below,

    $(document).ready(function(){
        // your click event
    
        // you change evnet
        $(document).on('change', '#onoff', function(){
          $(this).val(this.checked ? 'live' : 'all');
          sendAjaxRequest($(this),'{{ route('getScores') }}');
        });  
    });
    

    if its working now then you have facing an issue of "Delegated Event Binding"

    You have to use this method while elements are dynamically inserted or removed from the DOM. In your case, elements are dynamically inserted and removed on ajax call....