Laravel ajax "invalid or unexpected token" on .append

Viewed 367

I am trying to call my table contents using ajax append from a laravel controller function. I am getting this error though

1

Ajax:

    function fetchcategory() {
        $.ajax({
            type: "GET",
            url: "/clinical/bbr-category-configuration-data",
            dataType: "json",
            success: function (response){
                // console.log(response.all_categories);
                $.each(response.all_categories, function (key, item) {
                    $('tbody').append('<tr>\
                        <td>'+item.category_name+'</td>\
                        <td>'+item.category_name+'</td>\
                        <td>'+item.category_name+'</td>\
                        <td>'+item.category_name+'</td>\ 
                        </tr>');
                });
            }
        });
    }

Controller: (tabled retrieved form model HmsBbrCategory)

public function fetchcategory(){
    $all_categories = HmsBbrCategory::all();
    return response()->json([
        'all_categories'=>$all_categories,
    ]);
}

Route:

    Route::get('/bbr-category-configuration-data', [BBRCategoryConfigurationController::class,'fetchcategory']);

What syntax did I do wrong to get that unexpected token error, at first glance they seem to all encased inside the append. any help would be appreciated.

2 Answers

it's just javascript string syntax. you cant escape newline like this.

this version should work.

$('tbody').append('<tr>'+
  '<td>'+item.category_name+'</td>'+
  '<td>'+item.category_name+'</td>'+
  '<td>'+item.category_name+'</td>'+
  '<td>'+item.category_name+'</td>'+
'</tr>');

or better, with newer syntax.

$('tbody').append(`<tr>
  <td>${item.category_name}</td>
  <td>${item.category_name}</td>
  <td>${item.category_name}</td>
  <td>${item.category_name}</td>
</tr>`);

I can't pu my finger around it,

But VSCode doesn't like your posted text

I only delete all last character and added them new and voila it works

$.each(response.all_categories, function (key, item) {
    $('tbody').append('<tr>\
        <td>'+item.category_name+'</td>\
        <td>'+item.category_name+'</td>\
        <td>'+item.category_name+'</td>\
        <td>'+item.category_name+'</td>\
        </tr>');
});
Related