Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uhbc's avatar
Level 1

Ajax Get Method

Hi, i can send data to db with using ajax post for the chat but can't use the ajax get for showing off the data in the screen. Can anyone help me about that?

Here is my db:

CREATE TABLE `chat` (
  `id` int(11) NOT NULL,
  `chat` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `username` text NOT NULL,
  `userid` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

What i am currently using for retrieving data:

<div id="chat">
<ul class="list-group">
                          @foreach (App\ChatModel::chat() as $chat)
                          <li class="list-group-item" style="word-wrap:break-word;"><b>{{$chat->username}}</b>: {{$chat->chat}} </li>
                          @endforeach
                          </ul>
</div>

ChatModel:

  public static function chat(){
        $results = \DB::select(
          'SELECT * FROM (SELECT * FROM chat ORDER BY id DESC LIMIT 10) y ORDER BY y.id');


        return $results;

    }

I have to f5 the page to see what has just typed in the chat. Some said, i have to use the GET Method but i have no idea how to use it.

I used the $('#chat).load(' #chat); but thats not really effective. I want to get the data in the chat menu when a one is added. With a little animation

0 likes
90 replies
tykus's avatar

What JS framework/library are you using?

How are you displaying the Blade template (controller / route closure)?

uhbc's avatar
Level 1
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Route::get('/chat', 'HomeController@index')->name('getchat');
Route::post('/chat', 'ChatController@chat')->name('chat');
      public function chat(Request $request){
        $validate = $this->validate($request, [
          'chat'=> 'required|max:120|min:6',
        ]);
        if($validate){
          $info = ['chat'=>$request->chat,
                       'userid'=>\Auth::user()->id,
                       'created_at'=>now(),
                       'updated_at'=>now(),
                       'username'=>\Auth::user()->name
                     ];
        $uhbc = \DB::table('chat')->insert($info);
      }else{
        return ('dont.');
      }
      }
uhbc's avatar
Level 1

HomeController@index:

public function index(){
return view('home');
}
tykus's avatar

So the getchat route return a full view template (without data)?

uhbc's avatar
Level 1

I dont really know what to do, haven't seen a get method example before..

tykus's avatar

Ok. Here is what I would consider doing:

Create a reusable query scope of the ChatModel to fetch the most recent 10 chat messages:

// ChatModel.php

public function scopeRecent($query)
{
    return $query->latest('id')->take(10)->orderBy('id');
}

Return the homeview template along with the original data (fetched using that new query scope):

// HomeController.php

public function index(){
    //
    $chats = ChatModel::recent()->get();

    return view('home', compact('chats');
}

In the view, iterate over the Collection of ChatModel instances including a new chats/message view partial for each chat in the chats Collection (instead of making an Eloquent query in the view):

// home.blade.php

<div id="chat">
    <ul class="list-group">
        @each('chat.message', $chats, 'chat') 
    </ul>
</div>

Create the message.blade.php partial in a resources/views/chats directory:

// message.blade.php

<li class="list-group-item" style="word-wrap:break-word;">
    <b>{{$chat->username}}</b>: {{$chat->chat}}
</li>

Whenever you create a new Chat, return a rendered template as a string from the Controller:

// ChatController.php

public function chat(Request $request) {
    // validate will throw a ValidationException if it fails, so no checks required
    $this->validate($request, [
        'chat'=> 'required|max:120|min:6',
    ]);

    // Since you have an Eloquent model, I am using that rather than Query Builder
    $chat = ChatModel::create([
        'chat' => $request->chat,
        'userid' => \Auth::user()->id,
        'username' => \Auth::user()->name // do you really need to store the user's name as well as the ID?
    ]);

    return view('chats.message', compact('chat'))->render();
}

Inject the returned HTML response into the view whenever the AJAX call successfully completes:

$.ajax({
    url: '/chat',
    type: 'post',
    data: // your form data
    success: function (response) {
        $('#chat > .list-group').append(response); // response will be a HTML string
    }   
})
3 likes
uhbc's avatar
Level 1

i got this error :

Non-static method App\ChatModel::recent() should not be called statically
tykus's avatar

Sorry, that method should have been scopeRecent() - updated now above for clarity

uhbc's avatar
Level 1

Thanks but, now i have to f5 the page again to see what is written.

uhbc's avatar
Level 1

Isnt that possible to get data without refreshing page? automatically? with a little effect

tykus's avatar

i have to f5 the page again to see what is written.

Do you mean that the new chat message does not appear on the page whenever it has been added? Can you check the console to see if there were errors, because the code should work?

uhbc's avatar
Level 1

Yes, when i add a new message, i have to F5 the page to see it. Not automatically appearing.

Cronix's avatar

No idea what your code looks like now, but when you submit a new message, just return the newest data and append to the view. You should show your current code.

  1. Type message
  2. hit submit
  3. sends ajax request to controller
  4. adds new message to model
  5. retrieve and return newest messages
  6. append to view
uhbc's avatar
Level 1

I was using the exact code he wrote up there. After it didn't work, went back to the old one.

uhbc's avatar
Level 1

@Cronix when i hit submit and check the db, the 'This is a new data' text is in it. And when i wanna see the message in this here: http://prntscr.com/j1hses, i have to reload the page.

Cronix's avatar

Does your browsers developer tools show the correct data being returned from the ajax call?

tykus's avatar

What was being returned from the Controller method; did you get back a HTML string with the partial for the newly created chat? If everything had been working with the exception of rendering the new chat, why revert everything - the browsers console would have given you some indication of any errors that might have been occurring?

uhbc's avatar
Level 1
    <!-- CSRF Token -->
    <meta id="token" name="token" content="{{ csrf_token() }}">
<input type="text" id="chat" value="" placeholder="Type your message here.." maxlength="120" class="form-control" autocomplete="off"><br />
                      <input type="hidden" id="userid"  value="{{Auth::user()->id}}">
                      <input type="hidden" id="username" value="{{Auth::user()->name}}">
                      <input type="hidden" id="token" value="{{ csrf_token() }}">
                      <input type="submit" class="btn-info btn-muted" value="Send!" id="send">

scripts:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<link rel="stylesheet" href="{{asset('css/anim.css')}}">



<script>
$(document).ready(function(){
$('#send').click(function () {

  var chat = $('#chat').val();
  var username = $('#username').val();
  var userid = $('#userid').val();
  var token = $('#token').val();


$.ajax({
  type:"POST",
  url:"{{url('chat')}}",
  data:"chat=" + chat + "&userid=" + userid + "&username=" + username + "&_token=" + token,
  beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('content'));},
  success: function (response) {
        $('#chat > .list-group').append(response); // response will be a HTML string
    }

});
});
});

</script>
Cronix's avatar

I can see why you're having problems, you've altered quite a bit. The first problem that's obvious is the url (from your screenshot)

Add an ID to your form tag. I'll pretend it's "myform".

Then make the inputs like (I've altered this quite a bit):

<form id="myform">
    {{ csrf_field() }}
    <input type="text" name="chat" placeholder="Type your message here.." maxlength="120" class="form-control" autocomplete="off"><br />
    <input type="submit" class="btn-info btn-muted" value="Send!">
</form>
<script>
$(document).ready(function() {
    let myform = $('#myform');

    myform.on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            type:"POST",
            url:"/chat",
            data: myform.serialize(),
            success: function (response) {
                $('#chat > .list-group').append(response);
            }
        });
    });
});
</script>

I think that should be pretty close.

uhbc's avatar
Level 1

If i do this, the page will be reloaded and its not really cool for the chat. Also, it doesnt insert data to db.

Cronix's avatar

I don't think you copied everything correctly. The form shouldn't submit except by ajax. the e.preventDefault() makes it not submit the real form.

You also had numerous items with the ID of "chat". ID's need to be unique per page.

uhbc's avatar
Level 1

I changed the input id 'chat' into 'cett' and in from chatcontroller as well. Here is the data: http://prntscr.com/j1infc

but i still get the error '500 Internal Server Error'.

Cronix's avatar

Well changing the input name (not id) would alter your validation and saving too then. Did you update those?

look at your laravel error log to find out why there is a 500 error. Do you know how to troubleshoot? It seems you are trying to do too many things at once that you don't fully have a grasp on, which is making this a lot harder.

You're also not copying the code exactly as I (and Tykus) are supplying you. The form I'm sending only contains the "chat" and "_token" fields and grabbing the users id and name from Auth in the controller (so you don't have to send those in the form), but the screenshot you are showing has more.

uhbc's avatar
Level 1

In the codes Tykus sent has:

      $chat = ChatModel::create([
            'chat' => $request->cett,
            'userid' => \Auth::user()->id,
            'username' => \Auth::user()->name // do you really need to store the user's name as well as the ID?
        ]);

Dont i also have to send the user's name, to see who sent the messages and show it on the screen?

Cronix's avatar

No, it's getting it from the current logged in user here 'username' => \Auth::user()->name, just like userid.

Did you change the validation rule too from 'chat' to 'cett'?

What did the laravel error log say about the 500 error, or are you not getting that anymore?

uhbc's avatar
Level 1

Logs:

[2018-04-06 01:30:30] local.ERROR: Namespace declaration statement has to be the very first statement or after any declare call in the script {"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 64): Namespace declaration statement has to be the very first statement or after any declare call in the script at /var/www/0/public_html/app/Http/Controllers/ChatController.php:3)
[stacktrace]
#0 {main}
"} 


Cronix's avatar

Ok, that error is not from anything Tykus or I created.

Post your entire ChatController.

uhbc's avatar
Level 1
  <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use App\Http\Controllers\Auth;
use App\ChatModel;

class ChatController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function chat(Request $request) {
        // validate will throw a ValidationException if it fails, so no checks required
        $this->validate($request, [
            'cett'=> 'required|max:120|min:6',
        ]);

        // Since you have an Eloquent model, I am using that rather than Query Builder
        $chat = ChatModel::create([
            'chat' => $request->cett,
            'userid' => \Auth::user()->id,
            'username' => \Auth::user()->name // do you really need to store the user's name as well as the ID?
        ]);

        $view = view()->make('chats.message', compact('chat'));
        return $view->render();
    }



}

Next

Please or to participate in this conversation.