Grace
Grace

Reputation: 299

How to convert ajax response and use for-each loop in blade template?

i have this ajax response i'm bit confuse on how to convert this into foreach loop inside my blade template. what i'm trying to do is get the days in a month then display checkbox for each dates.

controller:

public function days(Request $request){
$days=array();
$id = $request->input('months');
$month = $id;
$year = 2018;
for($d=1; $d<=31; $d++) {
$time=mktime(12, 0, 0, $month, $d, $year);       
if(date('m', $time)==$month && date('w', $time)>0 && date('w', $time)<6) {
$days[]=date('Y-m-d H:i:s', $time);}}
return response()->json($days);}

Ajax:

$(document).ready(function(){
$('.testing').on('change',function(){
var test=$(this).val(); 
$.ajax({
 type:'get',
 url:'/days',
 data:{"months":test,"_token": "{{ csrf_token() }}"},
 success: function(data){
  $('#ajax_data').html(data);
 }}); });});

Blade

<select class="testing" name="test" id="test">
<option value="0" dissable="true" selected="true">Select</option>
<option value="1" >JAN</option>
<option value="2">FEB</option>
</select>@foreach($days as $day)<input type="checkbox"  name="days[]"  > @endforeach

Upvotes: 0

Views: 6092

Answers (1)

Ariel Pepito
Ariel Pepito

Reputation: 659

Just like @boussadjra said that you should removed foreach

<select class="testing" name="test" id="test">
<option value="0" dissable="true" selected="true">Select</option>
<option value="1" >JAN</option>
<option value="2">FEB</option>   
<div id="days"></div>



 $(document).ready(function(){
    $('.testing').on('change',function(){
        var test=$(this).val(); 
        $.ajax({
         type:'get',
         url:'/days',
         data:{"months":test,"_token": "{{ csrf_token() }}"},
         success: function(data){
                $("#days").empty();
                $.each(data,function(index,value){
                    $("#days").append('<input type="checkbox" value="'+value+'" name="days[]"  > '+value+'<br/>');
                });
            }
        });
    });
});

Upvotes: 2

Related Questions