Home > Enterprise >  Using Carbon in html response frm ajax
Using Carbon in html response frm ajax

Time:04-09

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]); 
}

CodePudding user response:

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.

CodePudding user response:

you cant use PHP in the response to ajax, you have two options whether to handle it in PHP before return response or use can handle it via js, also please check this moment.js Library its Javascript library that manipulates dates like Carbon library

should be something like that at render you html

var now = moment(new Date()); //todays date
var end = moment($item.updated_at); // another date

 $('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">'   moment.duration(now.diff(end))    '</label></td>\
                    \</tr>');
  • Related