I'm trying to use Ajax to refresh a part of the page that shows a small part of my database. My problem is that the result I'm trying to send back is in form of a (long) string and I can't find a way to send a string as an ajax response. I'm a total beginner in ajax and I don't know how to solve this problem.
This is what my ajax looks like :
$.ajax({
url: "{{ url('/news/lastfive') }}",
method: 'get',
success: function(result){
$('#machin').html(result);
}
});
And the php function (I'm working in Laravel so there are some laravel functions) :
public function lastfive(){
$liste = DB::table('news')->latest()->limit(5)->get();
$str = <<<HTML
<table>
......
<tbody>
HTML;
foreach ($liste as $elements){
$str .= '<tr>';
foreach($elements as $element){
$str .= <<<HTML
<td>$element->author</td>
<td>$element->message</td>
<td>$element->date</td>
HTML;
}
$str .= '</td>';
}
$str .= '</tbody></table>';
return response()->json(['success'=>$str]);
}
When I do this my string $str cannot be encoded to json format and it doesn't work.
I also tried this in the php :
public function lastfive(){
$liste = DB::table('news')->latest()->limit(5)->get();
$liste = json_encode($liste);
return response()->json($liste);
}
This time I manage to passe the data onto my html page, but it is much less convenient for the layout and there are problems with the encoding of non ascii characters. Is there a better solution here that I'm missing?
I hope this question is not too stupid ;)