Use of undefined constant post - assumed 'post' - php

I have a menu with some post categories:
<ul>
#foreach($categories->get() as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
When I click in the category, for example with id "1", through the menu I want to show the posts that belong to the category with id "1"in the "#posts" div.
So, the #posts div shows the last posts when the page is acessed at first, but after a category is clicked it should show the posts that belong to the clicked category. So I have the #posts div:
<div id="posts">
#foreach($posts as $post)
<div id="posts">
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
#endforeach
</div>
If the category with id "1" is clicked in the console appears the info of the only post that exist for now for that category with id "1":
{id: 1, title: "Title", description: "", …}
Now do you know how to show in the #posts div the posts that belong to the clicked category with the append method? Something like below (but like below dont works):
$('#posts').append(
<div id="posts">
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
</div>);
});
I have a FrontController index method that shows the homepage:
public function index(){
return view('home')
->with('categories', Category::orderBy('created_at', 'desc')->get())
->with('posts', Post::orderBy('created_at','desc')->get());
}
I also have a PostController that has a method postsFromCategory to get the posts from a selected category:
public function WhereHasCategory(Request $request)
{
$posts = Post::whereHas('categories', function ($categories) use (&$request) {
$categories->where('category_post.id',$request->id);
})->get();
return response()->json($posts);
}
Then in the index.blade.php I have the ajax:
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' +
+ '<h1>' + post.title + '</h1>';
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});

I have never coded in laravel so the syntax is going to be off, but I hope the gist sticks:
First, you should not use duplicate IDs like "posts". Try assigning "post" + $key to every div inside the foreach:
<div id="posts">
#foreach($posts as $key => $post)
<div id="post" + $key>
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
#endforeach
</div>
Now, if you are retrieving the post per category with this code:
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' +
+ '<h1>' + post.title + '</h1>';
});
you could try:
var newPosts = "";
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' +
+ '<h1>' + post.title + '</h1>';
});
$('#posts').html(newPosts);
let me know

Change id to class
<div class="posts">
#foreach($posts as $post)
<div id="posts">
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
#endforeach
</div>
The code $('#posts').append() is not needed since we can add it in success callback of ajax.
Chenge the ajax function to this
$.ajax({
url: '{{ route('category.posts') }}',
type: 'GET',
data : { id:category_id },
success:function(result){
$('#posts').empty();
var newPosts='';
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' +
+ '<h1>' + post.title + '</h1>';
});
$('#posts').html(newPosts);
},
error: function(error) {
console.log(error.status)
}
});

Related

Images not rendering in blade view after ajax call Laravel 7

I am working on a search filter, fetching data from db through ajax call, text data is rendering but the image is not rendering, the link is also present in console image tag, but not showing in the blade view... if I submit it through form it renders data and images as well, please guide me... Thanks
Here's my blade code:
#if (count($product)>0)
#foreach ($product as $row)
<div class="col-sm-6 col-lg-4 px-2 mb-3">
<div class="card shadow-sm">
<div class="card-img position-relative">
<div class="owl-carousel position-relative">
#if (count($row->images)>0)
#foreach($row->images as $images)
<div> <img class="w-100" height="180px" width="250" src="{{ asset('carchain_private/public/src/uploads/ImagesP'.$row->product.'/'.'u_'. $row->user_id.'/'.'qr_'.$row->id.'/' . $images->name) }}"></div>
#endforeach
#else
<div> <img src="{{URL::asset('src/img-market/car.jpg')}}" alt="image"> </div>
#endif
</div>
<div
class="imgs-num rounded-pill bg-white light-color d-inline-flex align-items-center px-2">
<img class="camera-icon mr-1"
src="{{URL::asset('src/img-market/camera-to-take-photos.png')}}" alt="camera icon">
{{count($row->images ?? '0')}}
</div>
</div>
Here's my controller code:
$product = DB::table('manual_lovers')->select("*")
->leftJoin('users','manual_lovers.user_id','=','users.id')
->leftJoin('location_manual_collectors','manual_lovers.id','=','location_manual_collectors.user_id')
->leftJoin('prices_manual_collectors','manual_lovers.id','=','prices_manual_collectors.user_id')
->select('manual_lovers.*','users.user_type','prices_manual_collectors.price','prices_manual_collectors.currency','location_manual_collectors.address','location_manual_collectors.latitude','location_manual_collectors.longitude')
->get();
if($request->ajax()){
$page = view('marketplace.search_results_append', compact('product'))->render();
return response()->json(array(['page' => $page, 'count' => $count]));
}
here's the ajax call:
<script>
$('#condition,#price_min,#price_max,#year_min,#year_max,#mileage_from,#mileage_to,#location,#latitude,#longitude,#distance_km,#search_make,#model,#search_body,#country,#color,#sort_by').on('change',function(e){
e.preventDefault();
var condition = $('#condition').val();
var price_min = $('#price_min').val();
var price_max = $('#price_max').val();
var year_min = $('#year_min').val();
var year_max = $('#year_max').val();
var mileage_from = $('#mileage_from').val();
var mileage_to = $('#mileage_to').val();
var location = $('#location').val();
var latitude = $('#latitude').val();
var longitude = $('#longitude').val();
var distance_km = $('#distance_km').val();
var search_make = $('#search_make').val();
var model = $('#model').val();
var search_body = $('#search_body').val();
var country = $('#country').val();
var color = $('#color').val();
var sort_by = $('#sort_by').val();
$.ajax({
beforeSend: function(){
$('.ajax-loader').css("visibility", "visible");
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:"{{route('advanced_search')}}",
method:"POST",
dataType:"json",
data:{
condition:condition,
price_min:price_min,
price_max:price_max,
year_min:year_min,
year_max:year_max,
mileage_from:mileage_from,
mileage_to:mileage_to,
location:location,
latitude:latitude,
longitude:longitude,
distance_km:distance_km,
search_make:search_make,
model:model,
search_body:search_body,
country:country,
color:color,
sort_by:sort_by
},
success:function(data) {
// console.log(data);
$('#result_count').html(data[0].count);
$('#search_results_append').html(data[0].page);
},
complete: function(){
$('.ajax-loader').css("visibility", "hidden");
},
});
});
</script>
Here's the console's picture:
Here's the blade's view:

Show conferences when "Country" is clicked is not working properly

I have a modal that has some cities. If the user clicks in a city then in the #conferences div it appears the conferences that have in the column "city" that clicked city. This is working fine.
My doubt is how to, if the user clicks in Country, instead of a city, how to get all conferences, independently of the city because if the user click in Country the results can be of any city.
Do you know how to achieve that?
With value attribute like "" "<a value="">Country</a>" when "Country" is clicked in the console appears:
" {message: "", "exception: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",…}" in file "/Illuminate/Routing/RouteCollection.php".
ConferenceController method to get the conferences of the clicked city:
public function getConferencesOfCity($slug)
{
$conferences = Conference::whereCity($slug)->get();
return response()->json($conferences);
}
Modal where the city links appears:
<div class="modal-body">
<div class="container">
<ul class="modal-list row">
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="" id="" value="">Country</a>
</li>
#foreach($cities as $city)
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="city" id="{{$city}}">{{$city}}</a>
</li>
#endforeach
</ul>
</div>
</div>
Route:
Route::get('conferences/where/city/{slug}','ConferenceController#getConferencesOfCity')->name('city.conferences');
jQuery ajax request:
$("a[name='city']").on('click', function(){
$('#showCities').html($(this).text());
var city = $(this).attr("id");
$.ajax({
url: '{{ route('city.conferences',null) }}/' + city,
type: 'GET',
success:function(result){
console.log(result)
$('#conferences').empty();
var newConferences='';
var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}";
$.each(result, function(index, conference) {
$('#modal2').modal('hide');
var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug);
newConferences += '<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">\n' +
' <h5 class="card-title">'+conference.name+'</h5>\n' +
<p class="card-text font-size-sm">'+conference.city+'</p>\n' +
' </div>\n';
});
$('#conferences').html(newConferences);
},
error: function(error) {
console.log(error.status)
}
});
});

Do you know why is appearing the error: GET 500 (Internal Server Error)? (Ajax get request)

I have following code the view to list the cities that exist for all conferences stored in a database.
For example, if there are 2 conference entries in the database and one has the city Newcastle, another has the city Leeds it should show in this modal Newcastle and Leeds -
<ul class="modal-list">
#foreach($cities as $city)
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="city" id="{{$city}}">{{$city}}</a>
</li>
#endforeach
</ul>
When the user click in some city it appears this error:
jquery.min.js:4 GET http://proj.test/conferences/where/city/Newcastle 500 (Internal Server Error)
When the user clicks in some city is done an ajax request to get the conferences that have the column "city" equal to the city clicked by the user:
$("a[name='city']").on('click', function(){
var city = $(this).attr("id");
$.ajax({
url: '{{ route('city.conferences',null) }}/' + city,
type: 'GET',
success:function(result){
console.log(result)
alert(result);
$('#conferences').empty();
var newConferences='';
var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}";
$.each(result, function(index, conference) {
var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug);
newEvens += '<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">\n' +
' <div class="card box-shaddow">\n' +
' <img class="card-img-top" src='+ conference.image +' alt="Card image cap">\n' +
' <div class="card-body">\n' +
' <p class="font-size-sm"><i class="fa fa-calendar" aria-hidden="true"></i> '+conference.start_date+'</p>\n' +
' <h5 class="card-title h6 font-weight-bold text-heading-blue">'+conference.name+'</h5>\n' +
' <p class="card-text font-size-sm"><i class="fa fa-map-marker" aria-hidden="true"></i> '+conference.place+', '+conference.city+'</p>\n' +
' </div>\n' +
' <div class="card-footer d-flex justify-content-between align-items-center">\n' +
' More' +
' <span class="font-weight-bold font-size-sm"></span>\n'
' </div>\n' +
' </div>';
});
$('#conferences').html(newConferences);
},
error: function(error) {
console.log(error.status)
}
});
});
Route:
ConferenceController getConferencesOfCity route:
Route::get('conferences/where/city/{slug}','ConferenceController#getConferencesOfCity')->name('city.conferences');
ConferenceController getConferencesOfCity method:
public function getConferencesOfCity(Request $request)
{
$conferences = Conference::whereCity('city', DB::raw($request->slug))->get();
return response()->json($conferences);
}
Do you know why I see the error?
There are a few things to change here:
1) You need to pass the variable slug that you're getting from the route into the constructor of the function. Request isn't needed since you're not doing anything else with it.
2) You're already using whereCity, so don't pass in the column name
3) DB::raw is really only needed for more complicated queries or passing in mysql functions
public function getConferencesOfCity($slug)
{
$conferences = Conference::whereCity($slug)->get();
return response()->json($conferences);
}

Delete row with ajax and delete the record on page too

I'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<a href="?delete='.$row['id'].'" class="del">
<i class="fa fa-trash "></i>
</a>
</div>
</div>
</div>
</li>
</ul>
This is inside the loop which display all records on page. This is the ajax function
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
And my delete.php is simple delete query
$stmt = $pdo->prepare("DELETE FROM comment where id = :id");
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();
Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined
Uncaught TypeError: Cannot read property 'replace' of undefined
The ajax part is from tutorial since I'm very unfamiliar with js/ajax.
What can be the problem here?
In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.
var parent = $(this).parent(); = <div class="comment-head">
which has no ID. Thus attr('id') returns undefined.
You can select the ul element this way:
var parent = $(this).closest('ul.comments-list.record');
How about this code: (make full use of jquery)
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<i onclick="del(<?=$row['id']?>)" class="fa fa-trash "></i>
</div>
</div>
</div>
</li>
your jquery becomes:
function del(i)
{
$.ajax({
type: 'get',
url: 'delete.php',
data: {'ajax':1,'delete':i},
success: function() {
get_list();
}
});
}
function get_list()
{
//make ajax call to get data from php
}
You are getting undefined because the parent you are fetching is this one:
<div class="comment-head">
As you can see that does not have an id. That is why you are getting undefined.
For reference, I do not believe that there is a replace() method in jQuery. What you might be looking for is a replaceWith() method. Please refer to the documentation for more information.
I do not believe that you need to do a replace anywhere. From what I can understand, you want to pass the row[id] as a parameter on your AJAX call. Instead of trying to do a replace, use data as shown below:
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
#comments-list {
border: 1px solid black;
}
</style>
<ul id="comments-list" data-id="1" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">Me</h6>
<a href="?delete=1" class="del">
click here
</a>
</div>
</div>
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
// Grab the id
var commentsBlock = $('#comments-list');
var id = commentsBlock.data('id');
console.log(id);
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + id,
success: function() {
commentsBlock.slideUp(300,function() {
commentsBlock.remove();
});
}
});
});
});
</script>

How to make Custom Pagination Component Using Laravel and Vue Js

I am using Laravel and Vue Js for the data listing and paginate data using vue component, without using component my code works fine but when i use component pagination bar is working but not sync with listing,
Here is my Html
<!DOCTYPE html>
<html>
<head>
<title>Users List</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
</head>
<body>
<div class="container" id="users">
<!-- Item Listing -->
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
</tr>
<tr v-for="user in users">
<td>#{{ user.name }}</td>
<td>#{{ user.email }}</td>
<td>#{{ user.created_at }}</td>
</tr>
</table>
<vue-pagination></vue-pagination>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/vue.resource/0.9.3/vue-resource.min.js"></script>
<script type="text/javascript" src="/js/users.js"></script>
</body>
</html>
And Here is my Vue Js Code
var VueComponent = Vue.extend({
template:
'<nav>' +
'<ul class="pagination">' +
'<li v-if="pagination.current_page > 1">' +
'<a href="#" aria-label="Previous" #click.prevent="changePage(pagination.current_page - 1)">' +
'<span aria-hidden="true">«</span>' +
'</a>' +
'</li>' +
'<li v-for="page in pagesNumber" :class="{\'active\': page == pagination.current_page}">' +
'{{ page }}' +
'</li>' +
'<li v-if="pagination.current_page < pagination.last_page">' +
'<a href="#" aria-label="Next" #click.prevent="changePage(pagination.current_page + 1)">' +
'<span aria-hidden="true">»</span>' +
'</a>' +
'</li>' +
'</ul>' +
'</nav>',
props: ['user'],
data: function() {
return {
pagination: {
total: 0,
per_page: 2,
from: 1,
to: 0,
current_page: 1
},
offset: 4,
}
},
computed: {
isActived: function () {
return this.pagination.current_page;
},
pagesNumber: function () {
if (!this.pagination.to) {
return [];
}
var from = this.pagination.current_page - this.offset;
if (from < 1) {
from = 1;
}
var to = from + (this.offset * 2);
if (to >= this.pagination.last_page) {
to = this.pagination.last_page;
}
var pagesArray = [];
while (from <= to) {
pagesArray.push(from);
from++;
}
return pagesArray;
}
},
ready : function(){
this.getUsers(this.pagination.current_page);
},
methods : {
getUsers: function(page){
this.$http.get('/user/api?page='+page).then((response) => {
this.$set('pagination', response.data);
});
},
changePage: function (page) {
this.pagination.current_page = page;
this.getUsers(page);
}
}
})
Vue.component('vue-pagination', VueComponent);
new Vue({
el: '#users',
data: {
users: [],
pagination: {
total: 0,
per_page: 2,
from: 1,
to: 0,
current_page: 1
},
offset: 4,
},
ready : function(){
this.getUsers(this.pagination.current_page);
},
methods : {
getUsers: function(page){
this.$http.get('/user/api?page='+page).then((response) => {
this.$set('users', response.data.data);
});
},
}
});
How to make this pagination work with vue js when using vue component Please Help me.
It is not that complicated. You just forgot to link your current page with your component. To do so , just change your code in HTML section
<vue-pagination></vue-pagination>
to
<vue-pagination :pagination="pagination" v-on:click="getUsers(pagination.current_page)"></vue-pagination>
In your js code , get rid of data function from VueComponent and add pagination props
.....
props: {
pagination: {
type: Object,
required: true
}
},
computed: {
pagesNumber: function () {
if (!this.pagination.to) {
......
Also, remove your getUsers method from VueComposent and combine with getUsers method in Vue main instance
getUsers: function(page){
this.$http.get('/user/api?page='+page).then((response) => {
this.$set('users', response.data.data);
this.$set('pagination', response.data);
});
I think, now your code should work as expected.

Categories