Search code examples
javascriptphphtmllaravelphp-carbon

Using Carbon in html response frm ajax


In the below code, I want to show updated some hours ago since the data is updated, but ' + $item.updated_at->diffInHours(now()) + ' giving following error Uncaught SyntaxError: expected expression, got '>' It is pointing at -> operator

Any Suggestion is appreciated, Thanks

index.blade.php

<script>
...

function fetchAllNames() {
        var _url = '{{ route("names.fetch.route") }}';
        $.ajax({
            type: "GET",
            url: _url,
            dataType: "json",
            success: function(response) {                        
                $('tbody').html("");
                $.each(response.name, function($key, $item) {
                    $('tbody').append('<tr>\
                        <td><input type="checkbox" id="sub_master" data-id="' + $item.id + '"></td>\
                        <td>' + $key + '</td>\
                        <td>' + $item.name + '</td>\                            
                        <td><label id="timeLabel">' + $item.updated_at->diffInHours(now()) + '</label></td>\
                    \</tr>');
                });
            }
        });               
    }

...
</script>

CustomController.php

public function FetchName() 
{ 
    $name = CandidateName::all(); 
    return response()->json(['name'=>$name]); 
}

Solution

  • Assuming $item.updated_at is a string with a datetime such as '2022-04-01 12:12:00'. You can define a javascript function

    function diffInHoursToNow(dateStr){
       var inputDate = new Date(Date.parse(dateStr));
       var diff = new Date().getTime() - inputDate.getTime();
       //depending on what you want you can round this off with 
       //Math.floor(diff/3600)/1000 or similar 
       return diff/3600000;
    }
    

    and then when generating your table row you can call

    <td><label id="timeLabel">' + diffInHoursToNow($item.updated_at) + '</label></td></tr>'
    

    Although it's valid and can be useful on occasion, you probably don't want to use $ to start your javascript variable names ($key and $item). This will help to remove the temptation to call php functions.