Laravel individual chat application - php

In my laravel project i have implemented a real time group chat that uses ajax but now I'm looking for a tutorial that is using a similar setup like mine. A system that makes a logged in user, able to send a message to another user by clicking on their name and sending them a message with ajax. I haven't found any tutorial yet that is using that concept.
My setup:
Here's the index of my group chat:
#extends('admin.app')
#section('content')
<div class="container">
<div class="row" style ="padding-top:40px;">
<h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
<br/><br/>
<div class="col-md-2">
<p>Users online</p>
#foreach($users as $user)
#if($user->isOnline())
<li>{{$user->FullName}}</li>
#endif
#endforeach
</div>
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
Recent Chat
</div>
<div class="panel-body">
<ul class="media-list" id="message">
#foreach($messages as $message )
<li class="media">
<div class="media-body">
<div class="media">
<div class="media-body" >
{{$message->message}}
<br/>
<bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
</small></bold>
<hr>
</div>
</div>
</div>
</li>
#endforeach
</ul>
<div>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Enter Message"/>
{{csrf_field()}}
<input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
<span class="input-group-btn">
<button type="submit" id="send" class="btn btn-info">Send</button>
</span>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(realTime, 2000);
});
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
},
});
setTimeout(realTime, 2000);
}
$(document).on('click','#send', function (){
$.ajax({
type:'post',
url:'/chat/send',
data:{
'_token':$('input[name=_token]').val(),
'from_name':$('input[name=from_name]').val(),
'message':$('input[name=message]').val(),
},
success: function (data) {
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
}
})
$('input[name=message]').val('');
});
</script>
#stop
here are the routes of my group chat:
Route::get('/chat', 'Chat\ChatController#index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController#sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController#getMessage' );
here's my controllers of the group chat:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users=user::all();
$messages=message::all();
return view('admin.chat.index',['messages'=> $messages],compact('users'));
}
public function sendMessage(Request $request){
$send = new Message();
$send ->from_name = $request->from_name;
$send ->message = $request->message;
$send->save();
return response()->json($send);
}
public function getMessage(){
$message = Message::all();
return response()->json($message);
}
here the migration for my group chat:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->string('from_name');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}

Related

Chat with laravel, socket io and redis not transferring messages through private channel

I am building a website with laravel, with chat option available inside it. I am able to store the messages in database as well as display in the sender's screen. But I can't manage to display the messages in receiver side. I am providing my codes as below. I used socket io and redis for the chat option.
server.js :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http,{
cors: { origin: "*"}
});
const port = process.env.PORT || 6001;
var Redis = require('ioredis');
var redis = new Redis();
var users =[];
http.listen(port, function () {
console.log(`Listening to port ${port}`);
});
redis.subscribe('private-channel', function() {
console.log('subscribed to private channel');
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
if (channel == 'private-channel') {
let data = message.data.data;
let receiver_id = data.receiver_id;
let event = message.event;
io.to(`${users[receiver_id]}`).emit(channel + ':' + message.event, data);
}
});
io.on('connection', function (socket) {
console.log('connection');
socket.on("user_connected", function (user_id) {
users[user_id] = socket.id;
io.emit('updateUserStatus', users);
console.log("user connected "+ user_id);
});
socket.on('disconnect', function() {
console.log('disconnected');
var i = users.indexOf(socket.id);
users.splice(i, 1, 0);
io.emit('updateUserStatus', users);
console.log(users);
});
});
controller :
public function companyconversation($userId) {
$users = \DB::table('users')->where([
'usertype'=>'individual',
])->get();
$friendInfo = User::findOrFail($userId);
$myInfo = User::find(Session::get('loginId'));
$company = $myInfo;
//$groups = MessageGroup::get();
$this->data['company'] = $company;
$this->data['users'] = $users;
$this->data['friendInfo'] = $friendInfo;
$this->data['myInfo'] = $myInfo;
$this->data['users'] = $users;
$this->data['userId'] = $userId;
//$this->data['groups'] = $groups;
//dd($users);
return view('company.convo', compact('users','friendInfo','myInfo','company'));
}
view :
<div id="main-content">
<div class="container-fluid">
<div class="block-header">
<div class="row clearfix">
<div class="col-md-6 col-sm-12">
<h1> Messages(Chat) </h1>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">Demo </li>
<li class="breadcrumb-item active" aria-current="page">Messages(Chat) </li>
</ol>
</nav>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 ">
<div class="card ">
<div class="body" style="height:100%; min-height:700px;">
<div class="chatapp_list">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search...">
<div class="input-group-append">
<span class="input-group-text"><i class="icon-magnifier"></i></span>
</div>
</div>
<div class="col-md-12">
<div class="users">
<h5>Users</h5>
<ul class="list-group list-chat-item">
#if($users->count())
#foreach($users as $users)
<li class="chat-user-list
#if($users->id == $friendInfo->id) active #endif">
<a href="{{ route('company_conversation', $users->id) }}">
<div class="chat-image media">
{!! makeImageFromName($users->fname,$users->lname) !!}
</div>
<div class="media-body">
<span class="name chat-name">{{$users->fname}}</span>
<!-- <span class="message">offline</span> -->
<span class="badge badge-outline status user-status-icon user-icon-{{$users->id}}"></span>
</div>
</a>
</li>
#endforeach
#endif
</ul>
</div>
</div>
</div>
<div class="chatapp_body">
<div class="col-md-9 chat-section">
<div class="chat-header">
<div class="chat-name font-weight-bold">
{{ $users->fname }}
</div>
</div>
<div class="chat-body" id="chatBody">
<div class="message-listing" id="messageWrapper" style="
border: 1px #ccc solid;
height: 100%;
overflow: hidden;
min-height: 450px;
position: relative;
z-index: 9;
color:#333;
background: #fff;
">
</div>
</div>
<div class="chat-box">
<div class="chat-input border text-secondary bg-white p-3 " id="chatInput" contenteditable="">
</div>
<div class="chat-input-toolbar">
<button title="Add File" class="btn btn-light btn-sm btn-file-upload">
<i class="fa fa-paperclip"></i>
</button> |
<button title="Bold" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('bold', false, '');">
<i class="fa fa-bold tool-icon"></i>
</button>
<button title="Italic" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('italic', false, '');">
<i class="fa fa-italic tool-icon"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Success -->
<div class="modal fade" id="adsuccessModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"> Successfully Saved </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="text-align: center;">
<span> <i class="fa fa-check-circle-o" style="font-size: 6em; color: #060;"></i> </span>
<h2 style="color: #060;"> Ad Saved Successfully</h2>
<button type="button" class="btn btn-round btn-success">
<i class="fa fa-bars"> Back to Ads Lists </i> </button>
</div>
<span style="font-size: 10px; color: #f00; text-align: center; margin-bottom: 1em;">Note: Your Ad will be automatically expired after 30 days of posted</span>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal END -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script>
<script>
function getCurrentTime() {
return moment().format('h:mm A');
}
function getCurrentDateTime() {
return moment().format('MM/DD/YY h:mm A');
}
function dateFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YY h:mm A');
}
function timeFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('h:mm A');
}
$(function (){
let $chatInput = $(".chat-input");
let $chatInputToolbar = $(".chat-input-toolbar");
let $chatBody = $(".chat-body");
let $messageWrapper = $("#messageWrapper");
let user_id = "{{ Session::get('loginId') }}";
//console.log(user_id);
let ip_address = '127.0.0.1';
let socket_port = '6001';
let socket = io(ip_address + ':' + socket_port);
let friendId = "{{ $friendInfo->id }}";
socket.on('connection',function() {
socket.emit('user_connected', user_id);
});
socket.on('updateUserStatus', (data) => {
let $userStatusIcon = $('.user-status-icon');
$userStatusIcon.removeClass('text-success');
$userStatusIcon.attr('title', 'Away');
console.log(data);
$.each(data, function (key, val) {
if (val !== null && val !== 0) {
let $userIcon = $(".user-icon-"+key);
$userIcon.addClass('text-success');
$userIcon.attr('title','Online');
}
});
});
$chatInput.keypress(function (e) {
let message = $(this).html();
if (e.which === 13) {
$chatInput.html("");
sendMessage(message);
return false;
}
});
function sendMessage(message) {
let url = "{{ route('send-message') }}";
let form = $(this);
let formData = new FormData();
let token = "{{ csrf_token() }}";
formData.append('message', message);
formData.append('_token', token);
formData.append('receiver_id', friendId);
appendMessageToSender(message);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'JSON',
success: function (response) {
if (response.success) {
console.log(response.data);
}
}
});
}
function appendMessageToSender(message) {
let name = '{{ $myInfo->fname }}';
let image = '{!! makeImageFromName($myInfo->fname,$myInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+getCurrentDateTime()+'">\n' +
getCurrentTime()+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' + message +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+ userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
function appendMessageToReceiver(message) {
let name = '{{ $friendInfo->fname,$friendInfo->lname }}';
let image = '{!! makeImageFromName($friendInfo->fname,$friendInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+dateFormat(message.created_at)+'">\n' +
timeFormat(message.created_at)+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
' <div class="message-text">\n' + message.content +
' </div>\n' +
' </div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
{
appendMessageToReceiver(message);
});
});
</script>
Event :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PrivateMessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('private-channel');
}
public function handle() {
}
}
I am expecting the message to appear on the receiver side, but it is not happening.

How can I display subcategories of specific category id in a dropdown. Within laravel

So after figuring out how to display categories and sub categories in a dropdown. I have been trying to figure out if its possible to display specific subcategories of a category class.
These are the Categories I set up
After making the categories I created subcategories the ones shown here are based on the first cat ID - selections
The cat and subcat were created as follows;
AppServiceProvider.php
<?php
namespace App\Providers;
use App\Category;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::share('categories', Category::orderBy('name')->get());
}
}
Web.php
<?php
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\SubcategoryController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('/Home', function () {
// return view('welcome');
//});
Auth::routes();
Route::get('/email', function () {
return new \App\Mail\NewUserWelcomeMail();
});
Route::post('follow/{user}', 'FollowsController#store');
Route::get('dashboard/profile', 'ProfilesController#show');
Route::get('/search','SearchController#search');
Route::get('/home', 'HomeController#index');
Route::get('/categories', 'CategoryController#index');
Route::get('/', 'PostsController#index');
Route::get('/p/create', 'PostsController#create');
Route::post('/p', 'PostsController#store');
Route::get('/p/{post}', 'PostsController#show');
//Route::prefix('/recipes')->group(function () {
// Route::get('/create-step1', 'RecipesController#createStep1');
// Route::get('/create-step2', 'RecipesController#createStep2');
// Route::get('/create-step3', 'RecipesController#createStep3');
// Route::get('/create-step4', 'RecipesController#createStep4');
// Route::post('/create-step1', 'RecipesController#postCreateStep1');
// Route::post('/create-step2', 'RecipesController#postCreateStep2');
// Route::post('/create-step3', 'RecipesController#postCreateStep3');
// Route::post('/create-step4', 'RecipesController#postCreateStep4');
// Route::post('/remove-image', 'RecipesController#removeImage');
//});
Route::get('/recipes/create', 'RecipesController#create');
Route::get('subcategories/get/{id}', 'RecipesController#getStates');
Route::get('/profile/{user}', 'ProfilesController#index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfilesController#edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfilesController#update')->name('profile.update');
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [];
public function subcategories(){
return $this->hasMany('App\Subcategory');
}
public function posts(){
return $this->hasMany('App\Post');
}
}
?>
RecipesController.php
<?php
namespace App\Http\Controllers;
use App\Recipe;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class RecipesController extends Controller
{
public function index()
{
return view('recipes.index');
}
public function create()
{
$categories = DB::table('categories')->pluck("name","id");
return view ('recipes.create', compact($categories));
}
public function getStates($id)
{
$subcategories = DB::table("subcategories")->where("category_id", $id)->pluck("name", "id");
return json_encode($subcategories);
}
}
recipes/create.blade.php
#extends('layouts.app')
#section('content')
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Multi Step Form | Recipes smartMeals</title>
</head>
<body>
<div class="container">
<header>Create Your First Recipe</header>
<div class="form-outer">
<form action="#">
<div class="page">
<div class="title">What's your recipe:</div>
<div class="field pt-1">
<div class="label pt-3">Title</div>
<input type="text" placeholder="Name the recipe">
</div>
<div class="field">
<label class="label pt-3">Description</label>
<div class="control pb-1">
<textarea class="textarea" placeholder="Lets cut to the cheese"></textarea>
</div>
<div class="field">
<button>Next</button>
</div>
</div>
</div>
<div class="page">
<div class="title pt-3">Recipe information:</div>
<div class="field is-horizontal pt-3">
<div class="field-label is-normal">
<label class="label">Selections</label>
</div>
<div class="field-body">
<div class="field is-narrow">
<div class="control">
<div class="select is-fullwidth">
<select>
<option value="">--Select Selections--</option>
#foreach($categories as $category)
<option>{{$category -> name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
<div class="field is-horizontal pt-3">
<div class="field-label is-normal">
<label class="label">Selections type</label>
</div>
<div class="field-body">
<div class="field is-narrow">
<div class="control">
<div class="select is-fullwidth">
<select name="subcatagories">
<option>--Select Selection Type--</option>
</select>
</div> <div class="col-md-2"><span id="loader"><i class="fa fa-spinner fa-3x fa-spin"></i></span></div>
</div>
</div>
</div>
</div>
<div class="field pt-2">
<label class="label">Message</label>
<div class="control">
<textarea class="textarea" placeholder="Lets cut to the cheese"></textarea>
</div>
<div class="field">
<button>Next</button>
</div>
</div>
</div>
</form>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>
<script src="{{ asset('js/custom.js') }}"></script>
</body>
</html>
#endsection
custom.js
$(document).ready(function() {
$('select[name="categories"]').on('change', function(){
var categoryId = $(this).val();
if(categoryId) {
$.ajax({
url: '/subcategory/get/'+categoryId,
type:"GET",
dataType:"json",
beforeSend: function(){
$('#loader').css("visibility", "visible");
},
success:function(data) {
$('select[name="subcategory"]').empty();
$.each(data, function(key, value){
$('select[name="subcategory"]').append('<option value="'+ key +'">' + value + '</option>');
});
},
complete: function(){
$('#loader').css("visibility", "hidden");
}
});
} else {
$('select[name="subcategory"]').empty();
}
});
});
I was hoping to change the section of code within recipes/create.blade.php;
<div class="field-body">
<div class="field is-narrow">
<div class="control">
<div class="select is-fullwidth">
<select>
<option value="">--Select Selections--</option>
#foreach($categories as $category)
<option>{{$category -> name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
To display the sub categories of category id{1}, is this possible?

How to implement AJAX on multiple laravel pagination

I have 2 LARAVEL paginations on one page, know i want to implement AJAX technology in order to achive paginations without reload of entire page. With one pagination ajax works perfectly but i have problems when i want to implement AJAX on second Laravel pagination. Does anyone can help me ?
First pagination
Second pagination
Controller
function successlogin(Request $request)
{
$posts= Post::orderby('created_at', 'desc')->paginate(3, ['*'], 'page_1s');
$documents= Document::orderby('created_at', 'desc')->paginate(2, ['*'], 'page_2s');
if ($request->ajax()) {
return view('presult', compact('posts'));
}
return view('main_page', ['posts'=>$posts,'documents'=>$documents]);
}
main_page
<section id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading" style="color: #d21826; font-weight: bold;">Vijesti</h2>
<hr class="my-4">
</div>
</div>
</div>
<div class="container">
#if(session('deletePost'))
<div class="alert alert-danger" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{{ session('deletePost') }}
</div>
#endif
<div id="tag_container">
#include('presult')
</div>
</div>
</section>
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading" style="color: white; font-weight: bold;">Službeni Dokumenti</h2>
<hr class="light my-4">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-12 mx-auto text-center">
<div id="table_container" class="table-responsive">
#include('table')
</div>
</div>
</div>
</div>
#if (Auth::user())
Dodaj Vijest
#endif
</section>
ajax_script for pagination
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page == Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function()
{
$(document).on('click', '.pagination a',function(event)
{
event.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var myurl = $(this).attr('href');
var page=$(this).attr('href').split('page_1s=')[1];
getData(page);
});
});
function getData(page){
$.ajax(
{
url: '?page_1s=' + page,
type: "get",
datatype: "html"
})
.done(function(data)
{
$("#tag_container").empty().html(data);
location.hash = page;
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
}

Realtime-notifications with ajax

Hello i'm a new developer and in my laravel project i have implemented a real time chat function with ajax but i also want to add a real time notification system with ajax so when a message is written all users are notified for that message it would be very helpful if you could help me
here's my index page :
#extends('admin.app')
#section('content')
<div class="container">
<div class="row" style ="padding-top:40px;">
<h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
<br/><br/>
<div class="col-md-2">
<p>Users online</p>
#foreach($users as $user)
#if($user->isOnline())
<li>{{$user->FullName}}</li>
#endif
#endforeach
</div>
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
Recent Chat
</div>
<div class="panel-body">
<ul class="media-list" id="message">
#foreach($messages as $message )
<li class="media">
<div class="media-body">
<div class="media">
<div class="media-body" >
{{$message->message}}
<br/>
<bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
</small></bold>
<hr>
</div>
</div>
</div>
</li>
#endforeach
</ul>
<div>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Enter Message"/>
{{csrf_field()}}
<input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
<span class="input-group-btn">
<button type="submit" id="send" class="btn btn-info">Send</button>
</span>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(realTime, 2000);
});
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
},
});
setTimeout(realTime, 2000);
}
$(document).on('click','#send', function (){
$.ajax({
type:'post',
url:'/chat/send',
data:{
'_token':$('input[name=_token]').val(),
'from_name':$('input[name=from_name]').val(),
'message':$('input[name=message]').val(),
},
success: function (data) {
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
}
})
$('input[name=message]').val('');
});
</script>
#stop
here's my routes :
Route::get('/chat', 'Chat\ChatController#index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController#sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController#getMessage' );
here's my controllers:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users=user::all();
$messages=message::all();
return view('admin.chat.index',['messages'=> $messages],compact('users'));
}
public function sendMessage(Request $request){
$send = new Message();
$send ->from_name = $request->from_name;
$send ->message = $request->message;
$send->save();
return response()->json($send);
}
public function getMessage(){
$message = Message::all();
return response()->json($message);
}
Sorry in advanced for the bad english but i am a foreigner
well you have to read this tutorial and implement like this....
https://laracasts.com/discuss/channels/general-discussion/step-by-step-guide-to-installing-socketio-and-broadcasting-events-with-laravel-51
$(window).load(realTime);
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
setTimeout(realTime, 2000);
},
});
}
}
Try this..

Laravel posting and comments , i cannot comment after i created a new post using ajax

when i refresh the page using the browser everything is working fine i could still comment and i could also add new post but the problem is when i create a new post(which means a post like a facebook post) i cannot comment anymore on any post. here is my Homeview :
<div class="All-Post-Display" id="PostRefresh">
<div class="container">
#foreach($latest as $late)
<div class="row">
<div class="col-md-5 col-md-offset-2">
<div class="outside-pannel">
<div class="person">
<img src="/styleimage/facebook.jpg">
<h2>{{$late->user->name}} {{$late->user->lastname}}</h2><br>
<h4>{{$late->created_at->diffForHumans()}}</h4>
</div>
<div class="body-of-post">
<p>{{$late->body}}</p>
</div>
<div class="like-comment-share">
<form>
<ul>
<li><i class="fa fa-thumbs-up"></i>Like</li>
<li><i class="fa fa-comments-o"></i>Comment</li>
<li><i class="fa fa-share"></i>Share</li>
</ul>
</form>
</div>
<div class="comment-section" >
<div class="total-likes">
<h3>3 likes your post</h3>
</div>
<div class="comment-form">
#foreach($late->comments as $comment)
<div class="display-comments">
<div class="comment-img">
<img src="/styleimage/facebook.jpg">
</div>
<div class="comment-container">
<div class="comment-content">
<a name="postername" href="#">rd</a> <span></span>
<div class="reply-like">
<ul>
<li>Like</li>
<li>Reply</li>
<li><h6>just now</h6></li>
</ul>
</div>
</div>
</div>
</div>
#endforeach
<div>
<div class="commenting-container">
<img src="/styleimage/facebook.jpg">
<textarea rows="1" id="comment-body{{$late->id}}" name="body" placeholder="Write a comment..."></textarea>
<input type="text" name="commentable" id="posting-id{{$late->id}}" value="{{$late->id}}" style="display: none;">
<div class="emojis">
<ul>
<li><i class="fa fa-smile-o"></i></li>
<li><i class="fa fa-camera-retro"></i></li>
<li><i class="fa fa-bookmark"></i></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$('#comment-body{{$late->id}}').keypress(function (e) {
if (e.which == 13) {
var comment = $('#comment-body{{$late->id}}').val();
var postCommentedId = $('#posting-id{{$late->id}}').val();
$.ajax({
url: '/comment',
type: 'post',
data: {'commentable_id':postCommentedId,'body':comment,'_token':$('input[name=_token]').val()},
success: function (data) {
console.log('success');
$('#comment-body{{$late->id}}').val(null);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}
});
});
</script>
#endforeach
</div>
</div>
</div>
{{csrf_field()}}
<script>
$( document ).ready(function() {
$('#ButtonPost').click(function (event) {
var thebody = $('#bodyPost').val();
$.ajax({
url: 'index',
type: 'post',
data: {'body':thebody,'_token':$('input[name=_token]').val()},
success: function (data) {
$('#PostRefresh').load(location.href + ' #PostRefresh');
$('#bodyPost').val(null);
}
});
});
});
</script>
after running this AJAX at the bottom the AJAX inside my #foreach doesn't work , id="PostRefresh" is gonna be refreshed when i make new post. im also using id="{{id of post}}" to make them unique in every post, Please Help Thank you...
Instead of this
$('#ButtonPost').click(function (event) ...
Try to use
$(document).on('click','#ButtonPost',(function (event) ...
Here the problem is, once you create new DOM then you don't have id of new element created to your jquery id not working.
But with this code you will get jquery code linked to every element of if #buttonPost.

Categories