How to implement AJAX on multiple laravel pagination - php

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');
});
}

Related

pop-up loading again and again in dashboard page

My purpose is when a user order a product need to get a notification in the dashboard page. Now the notification is getting . when i click Ok, let me check button in the dashboard its go to order listing page. but the problem is when i back to the dash baord the same order notication will coming. i need once i click, when i click Ok, let me check button the same order pop-up will not show
my Ajax
<script>
setInterval(function () {
$.get({
url: '{{route('get-order-data')}}',
dataType: 'json',
success: function (response) {
let data = response.data;
if (data.new_order > 0) {
playAudio();
$('#popup-modal').appendTo("body").modal('show');
}
},
});
}, 1000);
function check_order() {
location.href = '{{route('admin-order-pending')}}';
}
Function in Laravel
public function order_data()
{
$new_order = DB::table('orders')->where(['checked' => 0])->count();
return response()->json([
'success' => 1,
'data' => ['new_order' => $new_order]
]);
}
Pop-up code in dashboard
<div class="modal" id="popup-modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12">
<center>
<h2 style="color: rgba(96,96,96,0.68)">
<i class="tio-shopping-cart-outlined"></i> You have new order, Check Please.
</h2>
<hr>
<button onclick="check_order()" class="btn btn-primary">Ok, let me check</button>
</center>
</div>
</div>
</div>
</div>
</div>
try this..
<script>
setInterval(function () {
$.get({
url: '{{route('get-order-data')}}',
dataType: 'json',
success: function (response) {
let data = response.data;
if (data.new_order > 0) {
playAudio();
$('#popup-modal').appendTo("body").modal('show');
}
$('#popup-modal').appendTo("body").modal('none');
},
});
}, 1000);
function check_order() {
location.href = '{{route('admin-order-pending')}}';
}
Function in Laravel
public function order_data()
{
$new_order = DB::table('orders')->where(['checked' => 0])->count();
return response()->json([
'success' => 1,
'data' => ['new_order' => $new_order]
]);
}
Pop-up code in dashboard
<div class="modal" id="popup-modal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-12">
<center>
<h2 style="color: rgba(96,96,96,0.68)">
<i class="tio-shopping-cart-outlined"></i> You have new order, Check Please.
</h2>
<hr>
<button onclick="check_order()" class="btn btn-primary">Ok, let me check</button>
</center>
</div>
</div>
</div>
</div>
</div>
enter code here

Logging status of lesson to db when vimeo video complete via ajax and jquery

I am attempting to log data to my database when a vimeo video completes to in the end track students/employees time in a course as well determine when they have completed the course. I am lost when it comes to js and ajax. Below is what I have tried so far. I am using laravel 5.6.
If someone could even just point me into the right direction that would help tremendously.
#extends('layouts.app')
#section('page-title', trans('app.dashboard'))
#section('page-heading', trans('app.dashboard'))
#section('breadcrumbs')
<li class="breadcrumb-item active">
#lang('Companies')
</li>
#stop
#section('content')
#include('partials.toastr')
<div class ="row justify-content-md-center">
<div class='col-lg-6 '>
<iframe id="display" style="width:100%; height:360px;overflow:auto;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
<div class = "row">
<div class="col-lg-8 col-md-12">
<h2>Course Lessons</h2>
#include('courses.partials.lessons')
</div>
#permission('online.instructor.menu')
<div class="col-lg-4 col-md-12">
#include('courses.partials.instructor_menu')
</div>
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold">Add New Lesson</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
{!! Form::open(['route' => 'lesson.store', 'id' => 'lesson-form']) !!}
<div class="md-form mb-5">
<i class="fa fa-compass prefix grey-text"></i>
<input type="hidden" id="course_id" name="course_id" class="form-control validate" value="{{$course->id}}">
</div>
<div class="md-form mb-5">
<i class="fa fa-compass prefix grey-text"></i>
<input type="text" id="title" name="title" class="form-control validate">
<label data-error="wrong" data-success="right" for="title">Lesson Title</label>
</div>
<div class="md-form mb-5">
<i class="fa fa-sort prefix grey-text"></i>
<input type="text" id="order" name="order" class="form-control validate">
<label data-error="order" data-success="order" for="title">Number order to diplay.</label>
</div>
<div class="md-form mb-5">
<i class="fa fa-film prefix grey-text"></i>
<input type="text" id="content" name="content" class="form-control validate">
<label data-error="wrong" data-success="right" for="title">Lesson Content</label>
</div>
</div>
<div class="modal-footer d-flex justify-content-center">
<button class="btn btn-primary">Add Lesson</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endpermission
</div>
#stop
#section('styles')
#stop
#section('scripts')
<script>
function onFinish() {
status.text('finished');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function (e) {
e.preventDefault(); //**** to prevent normal form submission and page reload
$.ajax({
type : 'POST',
url : '{{route('lesson.completed')}}',
data : {
lesson: val({{$lesson->id}}),
user: val({{$auth->user-id}}),
time: val({{date('Y-m-d h:i:s')}})
},
success: function(result){
console.log(result);
$('#head').text(result.status);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
});
});
}
});
</script>
#stop
It appeared I had an error in my js, I rewrote the function and now have it working.
<script>
$(function() {
var iframe = $('#display')[0];
var player = $f(iframe);
var lesson_id='';
var lesson_complate_id='';
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
$('button').bind('click', function() {
lesson_id=$(this).data('id');
});
function onFinish() {
console.log('finished');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'X-Requested-With': 'XMLHttpRequest'
}
});
$.ajax({
url: '{{route('lesson.complete')}}',
method: 'POST',
data: {
lesson: lesson_id,
user: {{Auth::user()->id}},
course: {{$course->id}},
},
success: function(res){
lesson_complate_id ="#lesson_complate_id"+lesson_id;
$(lesson_complate_id).attr('class', 'badge badge-success');
$(lesson_complate_id).text('Completed')
}
});
}
</script>

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.

Implement VueJS with Laravel Blade?

I have create a two different feed component with Laravel and vue js, the first one is pure using laravel controller and passing the data to view. Another one is using controller and passing to vue.js file.
But i trying to combine two together since is would be more user friendly for me which is fetching data into view and binding with vue button.
i had tried with this code but having error.Is there possible to do that?
#foreach($feeds as $feed)
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow">
<div class="post-heading">
<div class="pull-left image">
<img src="{{$feed->user->avatar}}" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ $feed->user->name }}
made a post.
</div>
<h6 class="text-muted time">{{ $feed->created_at->diffForHumans() }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ $feed->content }}</p>
<div class="stats">
<like id="{{$feed->id}}"></like> <objection id="{{$feed->id}}"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
But the problems is how to passing the id into my vue which is
<like :id="post.id"></like>
<objection :id="post.id"></objection>
Here is my Feed.vue file
<template>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-0">
<div class="panel panel-white post panel-shadow" v-for="post in posts">
<div class="post-heading">
<div class="pull-left image">
<img :src="post.user.avatar" class="avatar" alt="user profile image">
</div>
<div class="pull-left meta">
<div class="title h5">
{{ post.user.name }}
made a post.
</div>
<h6 class="text-muted time">{{ post.created_at }}</h6>
</div>
</div>
<div class="post-description">
<p>{{ post.content }}</p>
<div class="stats">
<like :id="post.id"></like>
<objection :id="post.id"></objection>
<a href="#" class="stat-item">
<i class="fa fa-retweet icon"></i>12
</a>
<a href="#" class="stat-item">
<i class="fa fa-comments-o icon"></i>3
</a>
</div>
</div>
<comment :id="post.id"></comment>
</div>
</div>
</div>
</div>
<script>
import Like from './Like.vue'
import Comment from './Comment.vue'
import Objection from './Objection.vue'
export default{
mounted(){
this.get_feed()
},
components:{
Like,
Objection,
Comment
},
methods:{
get_feed(){
this.$http.get('/feed')
.then( (response)=>{
response.body.forEach( (post) =>{
this.$store.commit('add_post',post)
})
})
},
},
computed: {
posts(){
return this.$store.getters.all_posts
}
}
}
This is one of my Like components.
<template>
<button class="btn btn-basic" v-if="!auth_user_likes_post" #click="like()">
True {{ likers.length }}
</button>
<button class="btn btn-primary" v-else #click="unlike()">
Untrue {{ likers.length }}
</button>
<script>
export default {
mounted(){
},
props: ['id'],
computed: {
likers() {
var likers = []
this.post.likes.forEach( (like) => {
likers.push(like.user.id)
})
return likers
},
auth_user_likes_post() {
var check_index = this.likers.indexOf(
this.$store.state.auth_user.id
)
if (check_index === -1)
return false
else
return true
},
post() {
return this.$store.state.posts.find( (post) => {
return post.id === this.id
})
}
},
methods: {
like() {
this.$http.get('/like/' + this.id)
.then( (resp) => {
this.$store.commit('update_post_likes', {
id: this.id,
like: resp.body
})
})
},
unlike() {
this.$http.get('/unlike/' + this.id)
.then( (response) => {
this.$store.commit('unlike_post', {
post_id: this.id,
like_id: response.body
})
})
}
}
}
Can you take a look at this https://scotch.io/tutorials/implement-a-favoriting-feature-using-laravel-and-vue-js, might be helpful.
It explains in details how you setup the Model in a proper way, the computed, and methods, also the steps are just too easy to follow.
I noticed that you have:
mounted(){
//blank
}
You could add some functionality like:
mounted() {
this.isFavorited = this.isFavorite ? true : false;
}
This will help handle the toggle part

Categories