Reputation: 307
How fetch data from a mysql database using ajax (laravel)? How to update the block dynamically .message_box
AJAX
$(function () {
$.ajax({
url: "",
dataType: 'html',
success: function(responce){
$('.message_box').html(responce); // this div to be updated
}
});
});
Blade
<div class="message_box">
@foreach($message as $content)
{{ $content->message }}
@endforeach
</div>
Controller
public function chat()
{
$message = MessageModel::orderBy('id')->get();
return view('chat.chat', ['message' => $message]);
}
Updated code
Upvotes: 2
Views: 1424
Reputation: 153
Did you add a url to your ajax request?
Route::get('/chat', 'ChatController@chat');
function update() {
$.ajax({
url: "/chat",
dataType: 'html',
success: function(responce){
$('.message_box').html(responce);
}
});
}
$('#send_message').submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
url: "/chat",
context: this,
data: $(this).serialize(),
cache: false,
async: true,
success: function () {
$('#message').val('');
update();
},
error: function () {
alert('Сообщение не было отправлено');
}
});
});
Upvotes: 3