2

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

2
  • 1
    Where is the database query? What is the problem? Commented Dec 26, 2015 at 19:07
  • @Vohuman, Updated code Commented Dec 26, 2015 at 19:11

1 Answer 1

3

Did you add a url to your ajax request?

Routes

Route::get('/chat', 'ChatController@chat');

AJAX

      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('Сообщение не было отправлено');
            }
        });

    });
Sign up to request clarification or add additional context in comments.

8 Comments

yes, but .message_box is not updated (if add new content).
the ajax is being called only once; when the page first loads. Is the chat in real time?
Are you using additional code, or is this the only code you are using for a real time chat? Are you using node?
If you want the chat to update when you click send message, then you can just call the update method as shown about. But if you want to chat with other users, then I suggest looking at nodejs and socket.io.
hm, sorry, but, div.message_box not refreshing :( (copy + past)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.