Cannot read property 'submit' of null i use laravel and javascript - javascript

I want to add a product to my favorites, but I do not want to make a load for the entire page, so I use JavaScript as shown in the code where I made an ancor disruption and created a form and took an id from the form and implemented it by using the submit function, but the following error appears and does
Uncaught TypeError: Cannot read property 'submit' of null
Please advise the importance
Thank you
this view
<div class="product-info">
<div class="tab-content" id="myTabContent">
<!-- Start Single Tab -->
<div class="tab-pane fade show active" id="man" role="tabpanel">
<div class="tab-single">
<div class="row">
#foreach($products as $p)
<div class="col-xl-3 col-lg-4 col-md-4 col-12">
<form action="{{route('cart.store')}}" method="post" id="add-cart-{{$p->id}}">
{{ csrf_field() }}
<input type="hidden" name="id" value="{{$p->id}}">
<input type="hidden" name="Product_Name_ar" value="{{$p->Product_Name_ar}}">
<input type="hidden" name="Price" value="{{$p->Price}}">
<div class="single-product">
<div class="product-img">
<a href="{{route('product', ['product' => $p->id])}}">
<img class="default-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
<img class="hover-img" src="{{ asset('images/products/'.$p->image) }}" alt="#">
</a>
<div class="button-head">
<div class="product-action">
#if(Auth::guard('customer')->check())
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="document.getElementById('favorite-{{$p->id}}').submit()" class="{{ Auth::guard('customer')->user()->favorite_products()->where('product_id', $p->id)->count() != 0 ? 'favorite' : '' }}">
<i class="fa fa-heart "></i><span>Add to Favorite</span></a>
<form id="favorite-{{$p->id}}" action="{{route('product.favorite', $p->id)}}" method="post">
{{ csrf_field() }}
</form>
#else
<span class="favorite-count">{{ $p->favorite_to_customers->count() }}</span>
<a title="Wishlist" href="javascript:void (0);" onclick="toastr.info('To add favorite list you to need login first', 'info', {
closeButton: true,
progressBar: true
})">
<i class="fa fa-heart "></i>
<span>Add to Favorite</span></a>
#endif
</div>
<div class="product-action-2">
<button style="background: transparent; border: none; color: black" class="btn btn-warning">Add to chart</button>
</div>
</div>
</div>
<div class="product-content">
<h3>{{ $p->Product_Name_ar }}</h3>
<div class="product-price">
<span>{{ $p->Price }} K.D</span>
</div>
</div>
</div>
</form>
</div>
#endforeach
</div>
</div>
</div>
<!--/ End Single Tab -->
</div>
</div>
This Controller
class Favoritecontroller extends Controller
{
public function add($id) {
$customer = Auth::guard('customer')->user();
$isFavorite = $customer->favorite_products()->where('product_id', $id)->count();
if($isFavorite == 0) {
$customer->favorite_products()->attach($id);
}else {
$customer->favorite_products()->detach($id);
}
return redirect()->back();
}
}
This Route
Route::group(['middleware' => ['auth:customer']], function () {
Route::post('favorite/{id}/add', 'FavoriteController#add')->name('product.favorite');
});

I assume your JS fails here
... onclick="document.getElementById('favorite-{{$p->id}}').submit()"
The proper way to do it
... onclick="addToWhishList({{$p->id}})"
Then in your JS
<script>
function addToWhishList(formId) {
//console.log(formId);
document.getElementById('favorite-' + formId).submit();
}
</script>
Check working Demo

Related

Corousel bootstrap for products in django ecommerce website?

I am trying to do slider for my products which should be only 4 products. I took code from resourses from the internet, but I have a problem to implement it. It's not working. In the below, you can see my code. As, I mentioned, I only want it to show four products, which means first row and slider.
html
<div class="angle angle-left prev"><img src="{% static 'images/angle-left.png' %}"></div>
<div class="row owl-corousel" style="width:80%;position: relative; left:10%;">
{% for product in products %}
<div class="store col-lg-3 col-6 owl-item">
<div class="single-product">
<div class="single-product">
<div class="header-single-product">
<p style="margin-top:-10px;margin-bottom:-10px" class="code">Код: 51265</p>
{% if product in wishedProductsList %}
<i class="bi bi-heart-fill addWishlist" style="color: red" data-product="{{product.id}}" data-action="add"></i>
{% else %}
<i class="bi bi-heart addWishlist" data-product="{{product.id}}" data-action="add"></i>
{% endif %}
<i class="fa fa-balance-scale" style="margin-right:5px;"></i>
</div>
<div class="product-image">
<img style="width: 100%;height: 100%;" src="{{product.imageURL}}">
</div>
<p style="color:#617375;">В наличии</p>
<p style="color:black;">{{product.name}}</p>
<p>.....</p>
<p>.....</p>
<p>.....</p>
<p class="price">Цена: {{product.price}}</p>
<div class="counter">
<div class="arrow-up increase" id="arrow-up" data-product="{{product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
<div class="quantity"><input type="number" class="quantity" value="1" data-product="{{product.id}}"></div>
<div class="arrow-down increase" id="arrow-down" data-product="{{product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
</div>
<div class="product-foot"><div class="product-action-2">
<button data-product="{{product.id}}" style="width:100%;height: 50px;" data-action="add" class="btn btn-outline-secondary add-btn update-cart">В Корзину</button>
</div></div>
</div>
</div>
</div>
{% endfor %}
<div class="angle angle-right next" style="float:right;"><img src="{% static 'images/angle-right.png' %}"></div>
</div>
script
<script>
$(document).ready(function()
{
if($('.row').length)
{
var viewedSlider = $('.row');
viewedSlider.owlCarousel(
{
loop:true,
margin:30,
autoplay:true,
autoplayTimeout:6000,
nav:false,
dots:false,
responsive:
{
0:{items:1},
575:{items:2},
768:{items:3},
991:{items:4},
}
});
if($('.prev').length)
{
var prev = $('.prev');
prev.on('click', function()
{
viewedSlider.trigger('prev.owl.carousel');
});
}
if($('.next').length)
{
var next = $('.next');
next.on('click', function()
{
viewedSlider.trigger('next.owl.carousel');
});
}
}
});
</script>
However, it's showing all pictures and is not working. So, can someone tell what is the problem. If I need any specific classes that should be used can you tell me these classes in such way that doesen't affect to my design. Thanks!

Undefined variable: products in #foreach

I'm facing some issues with a project build with Laravel
i want to show more then 12 product but i don't know what to change. this show only 12 product and i want 60 product to show. please help me. I've tried many solutions but its not working.
<div class="products-box-bar p-3 " >
<div class="row sm-no-gutters gutters-5">
#foreach ($products as $product)
<div class="col-xxl-3 col-xl-4 col-lg-3 col-md-4 col-6" >
<div class="product-box-2 bg-white alt-box my-md-2" style="border: 1px solid #f1f1f1;border-radius: 8px;">
<div class="position-relative overflow-hidden">
<a href="{{ route('product', $product->slug) }}" class="d-block product-image h-100 text-center" tabindex="0">
<img class="img-fit lazyload" src="{{ asset('frontend/images/placeholder.jpg') }}" data-src="{{ asset($product->thumbnail_img) }}" alt="{{ __($product->name) }}">
</a>
<div class="product-btns clearfix">
<button class="btn add-wishlist" title="Add to Wishlist" onclick="addToWishList({{ $product->id }})" type="button">
<i class="la la-heart-o"></i>
</button>
<button class="btn add-compare" title="Add to Compare" onclick="addToCompare({{ $product->id }})" type="button">
<i class="la la-refresh"></i>
</button>
<button class="btn quick-view" title="Quick view" onclick="showAddToCartModal({{ $product->id }})" type="button">
<i class="la la-eye"></i>
</button>
</div>
</div>
<div class="p-md-3 p-2">
<h2 class="redbaba">
<a href="{{ route('product', $product->slug) }}" class="product-title p-0 text-truncate-2" >
#if(home_base_price($product->id) != home_discounted_base_price($product->id))
<img class="sale654" src="{{ route('home') }}/ufo/img/sale.png"></img>
#endif
{{ __($product->name) }}
</a>
</h2>
<div class="price-box">
<span class="product-price strong-600" style="display: block;">{{ home_discounted_base_price($product->id) }}</span>
#if(home_base_price($product->id) != home_discounted_base_price($product->id))
<del class="old-product-price strong-400">BDT {{ home_base_price($product->id) }}</del>
#if (\App\Addon::where('unique_identifier', 'club_point')->first() != null && \App\Addon::where('unique_identifier', 'club_point')->first()->activated)
<span class="clubpoint02">⛬ Point {{ $product->earn_point }}</span>
#endif
#endif
</div>
<h2 class="djhfgj">
{{ __($product->shipping_type) }} shipping
</h2>
<div class="star-rating star-rating-sm mt-1" >
{{ renderStarRating($product->rating) }}
</div>
<p class="numberofsale">{{ __($product->num_of_sale) }} Sold</p>
</div>
</div>
</div>
#endforeach
</div>
</div>
<nav aria-label="Center aligned pagination" >
<ul class="pagination justify-content-center" style="background-color: #fff;padding: 10px 0;border-radius: 10px;margin-top: 15px;">
{{ $products->links() }}
</ul>
</nav>
In your App\Http\ProductsController.php or whichever file you use in fetching products from the database, you should see a function paginate(12), change it to paginate(60)
The title of your post is a little confusing as it doesn't match your description, I'll do my best to help though!
Undefined Variable: $products
This will most likely be due to the controller not passing a variable to the blade template.
In your controller, make sure that you are passing the variables to the view like so:
public function index() {
// Your logic here
return view('my-index', [
'products' => $products
]);
}
Pagination Limits
Displaying 12 items rather than 60 will be due to the limits passed to the paginate() function within the controller. Make sure you have set this to 60
public function index() {
// Retrieve up to 60 products at a time
$products = Product::paginate(60);
return view('my-index', [
'products' => $products
]);
}
Forelse loops
You may want to consider using a #forelse loop rather than a #foreach loop in case you don't have any products being returned from the query
#forelse($products as $product)
// Display your products
#empty
// Display a message saying no products were found
#endforelse

comment reply system with catching specific id value

hi guys I have a blog post page and comment and reply system. Everything works fine except one thing:
When I try to add a reply to a comment, I am always replying to the first comment. I think my fault is I can't reach the specific comment id when I click. Here is my html and ajax code:
HTML CODE
<div class="card" style=" margin-bottom:30px;">
<div class="card-header">
<a class="h3">#Model.Header</a>
<br />
<br />
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<p style="font-size:small">
<b>Kategori: </b> #Model.Category.CategoryName ,<b>Makale Sayısı :</b> #Model.Category.Articles.Count()
<b>Yorum Sayısı :</b> #Model.Comments.Count() <br />
<b>Yayımlanma Tarihi: </b> #String.Format("{0: d MMMM yyyy}", Model.Date) ,<b>Etiketler:</b><i class="fa fa-tags"></i> #Model.Tags.Count()
</p>
<p style="font-size:small;">
<img class="rounded-circle img-fluid" style="width:100px;height:100px;" src="#Model.User.Photo" alt="#Model.User.FullName" />
Posted by:
#Model.User.UserName
</p>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12">
<img id="articlephoto" style="width:100%; height:350px" class="rounded float-left" src="#Model.Photo" alt="Card image cap">
</div>
</div>
<div class="row" style="margin-top:20px">
<div class="col-md-12 col-xs-12 col-xl-12">
<p>#Html.Raw(Model.Paragraph)</p>
<p style="font-size:small">
<b>Etiketler:</b>
#foreach (var item in Model.Tags)
{
<span class="tag">#item.TagName,</span>
}
</p>
</div>
</div>
</div>
</div>
<h4>Comments</h4>
<hr />
#foreach (var item in Model.Comments.ToList())
{
<!-- Single Comment -->
<div class="media mb-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body" style="width:400px;">
<h5 class="mt-0">#item.User.UserName</h5>
<p style="word-break:break-all">
#item.Paragraph
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteComment/#item.CommentId">
Delete
</a>
<a class="btn btn-warning replybutton" href="#replyform">
Reply
</a>
}
</p>
<p style="font-size:small"><b>Yorum Tarihi:</b>#String.Format("{0: d MMMM yyyy}", item.Date)</p>
<span id="astar" class=""> #item.CommentId</span>
#foreach (var reply in Model.ReplyComments.Where(x => x.CommentId == item.CommentId).ToList())
{
<div class="media mt-4">
<img style="height:40px; width:40px;" class="d-flex mr-3 rounded-circle" src="#item.User.Photo" alt="#item.User.FullName">
<div class="media-body">
<h5 class="mt-0">#reply.User.UserName</h5>
<p>#reply.Paragraph</p>
#if (Convert.ToInt32(Session["UserId"]) == item.UserId)
{
<a class="btn btn-danger" href="/Home/DeleteReply/#reply.ReplyCommentId">
Sil
</a>
}
</div>
</div>
}
</div>
</div>
<hr />
}
#if (Session["UserId"] != null)
{
<!-- Comments Form -->
<div id="commentform" class="card my-4">
<h5 class="card-header">Yorum Yap:</h5>
<div class="card-body">
<form>
<div class="form-group">
<textarea id="comment" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary">Yorum Yap</button>
</form>
</div>
</div>
<div id="replyform" class="card my-4 d-none">
<h5 class="card-header">Cevap Yaz:</h5>
<div class="card-body">
<div class="form-group">
<textarea id="replytext" name="replytext" typeof="text" class="form-control" rows="3"></textarea>
</div>
<button type="submit" id="reply" name="reply" class="btn btn-primary">Cevap Yaz</button>
</div>
</div>
}
else
{
<div class="row" style="margin-bottom:30px;">
<div class="col-md-6">
<h3 class="alert- alert-heading">Yorum Yapabilmek İçin Üye Girişi Yapmalısınız.</h3>
</div>
</div>
}
AND my javascript ajax code
<script type="text/javascript">
$(document).ready(function () {
$("#reply").click(function (e) {
var r_comment = $("#replytext").val();
var r_commentid = parseInt($("#astar").html());
$.ajax({
url: '/Home/ReplyComment/',
data: { replycomment: r_comment, articleid:#Model.ArticleId, commentid: r_commentid },
type: 'POST',
dataType: 'json',
success: function (data) {
alert("Cevap gönderildi");
window.location.reload();
}
});
});
})
</script>
My problem is that I can't catch the specific comment id when I click the reply button. I am getting the comment id from <span id="astar" class=""> #item.CommentId</span>
"When I try to add a reply to a comment, I am always replying to the first comment. " - it's because all your comments have the same ID and jQuery selects the first matching element.
All comments need to have a unique ID. I don't know what language that loop is in but you need to increment the ID. So astar-1, astar-2, astar-3 etc...
Example;
$(document).ready(function(){
var valueBox = document.getElementById('value-box');
$('.reply').on('click', function(){
var comment = $(this).prev().attr('id');
valueBox.innerHTML += '<br />Reply to comment: ' + comment;
console.log(comment);
});
});
.comment::after {
display: table;
content: ' ';
clear: both;
}
span {
display: block;
float: left;
width: 45%;
}
.reply {
display: block;
float: right;
width: 45%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment">
<span id="comment-1">Yorum 1</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-2">Yorum 2</span>
<div class="reply">Cevapla</div>
</div>
<div class="comment">
<span id="comment-3">Yorum 3</span>
<div class="reply">Cevapla</div>
</div>
<div id="value-box">
</div>

How to add a "required" checkbox in this code

I want a checkbox in this code. Only if the checkbox is checked it should be possible to press upload / or to allow a upload.
Could you give me a hint how it's possible to change this?
Actually I can insert a checkbox but it's always uploading if the checkbox is unchecked.
#extends('master/index')
#section('custom')
<!-- Main page -->
<div id="content-wrapper" class="snap-content">
<!-- Progress bar -->
<div class="container progress-holder">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="progress-rate">--%</div>
<div class="progress">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">--% Complete</span>
</div>
</div>
</div>
</div>
</div>
<!-- Drag zone -->
#if($limitReached == true)
<div class="container text-center start-zone">
<p>{{ t('You have reached daily upload limit') }}</p>
</div>
#else
<div class="container text-center start-zone">
<form id="fileupload" action="{{ route('images.upload') }}" method="POST" enctype="multipart/form-data" accept="image/gif, image/jpeg, image/jpg, image/png">
<input type="file" id="input-browse" class="block-hide" multiple="multiple" name="files">
<p>{{ t('Drag photos from your computer in here. Select maximum 10 images') }}</p>
<div class="help-block">{{ t('Maximum file size allowed is') }} {{ maxUploadSize()*1024 < (int)siteSettings('maxImageSize')*(1024) ? maxUploadSize() : (int)siteSettings('maxImageSize') }}MB (o.O)</div>
<p>{{ t('You can also') }} <a class="browse_files" href="#">{{ t('browse') }}</a> {{ t('for photos to upload') }}.</p>
</form>
</div>
#endif
<div class="uploader block-hide">
<!-- Preview zone -->
<div class="container preview-zone">
<img src="{{ asset('static/img/mask-tran.png') }}"/>
</div>
<!-- Thumbnail zone -->
<div class="container thumbnail-zone">
<div class="row">
<div class="col-md-9">
<ul class="thumbnails-holder nav nav-tabs" id="myTab"></ul>
</div>
<div class="actions col-md-3 text-right">
<button type="button" class="btn btn-danger btn-remove"><i class="glyphicon glyphicon-trash"></i> remove</button>
<button type="button" class="btn btn-primary btn-upload"><i class="glyphicon glyphicon-open"></i> upload</button>
<p class="help-block"><span class="readyphoto"></span>/<span class="totalphoto"></span> photos are ready</p>
</div>
</div>
</div>
<!-- Edit zone -->
<div class="container-fluid tab-content edit-zone-holder"></div>
</div>
</div>
You can do this with JavaScript using the onchangeevent event to enable/disable button based on checked value
<input type="checkbox" onchange="document.getElementById('uploadButton').disabled = !this.checked;" />
<input type="submit" id="uploadButton" value=" Upload " />
you can disable and enable buttons with jQuery depending on the checkbox selection.
If you have:
<input type="checkbox" id="checkbox"/>
<button id="upload">Upload</button>
Then in your jQuery:
$("#upload").prop('disabled', true);
$("#checkbox").bind('change', function(){
var checked = this.checked;
if(checked){
$("#upload").prop('disabled', false);
} else {
$("#upload").prop('disabled', true);
}
});
JSFiddle
add a checkbox
<input type="checkbox" name="chk" id="chk" value="yourvalue">
add onclick event in your upload button
<button type="button" onclick="selected()">upload</button>
<script>
function selected()
{
if(document.getElementById('chk').checked) {
document.getElementById("fileupload").submit();
} else {
alert('YOUR CUSTOM MESSAGE');
}
}
</script>
Try this:
Add this in your html form.
<input type="checkbox" name="writeSomeName" value="value">
Then after that write some php code:
if ($_POST['writeSomeName'] == 'value')
{
//Add code for upload file here
}
else
{
echo "You have not checked the checkbox. Please make it check first"
}

Uncaught referenceerror is not defined - adding javascript function when Angular is being used

I am familiar with Javascript and Jquery, but fairly new to angular. I have used jquery in the past with angular, but this application that I inherited is causing my severe grief.
I click on button and get:
Uncaught ReferenceError: addComment is not defined
Code:
<div ng-controller="TipsCtrl" class="container" id="tips">
<div class="grid" style="margin-bottom: 0" >
<div class="col-1-4">
</div>
<div style="text-align: center" class="col-1-2">
<label class="text-blue text-center">Sort By:</label>
<select style="width:30%" ng-init="order='created'" class="input" ng-model="order">
<option value="created">Date Created</option>
<option value="createdBy">Created By</option>
<option value="getCategory()">Category</option>
</select>
<button data-tooltip="Reverse the sorting order."
class="btn-blue" ng-click="reverse=!reverse">Reverse</button>
</div>
<div class="col-1-4 text-right">
<button ng-click="createEmptyTip()" style="vertical-align: bottom" class="btn-blue">Add</button>
</div>
</div>
<div class="col-1-1" ng-if="!!error">
<div class="panel">
<span class="text-red">Error:</span> {{ error }}
</div>
</div>
<div update="resultsUpdated" paginate="page in tips" order="order" reverse="reverse" url="true">
<div style="margin-bottom: 20px">
<div paginate-controller></div>
</div>
<div ng-repeat="tip in page" class="tip"
id="tip-{{ tip.id }}" async-anchor async-anchor-delay="500">
<div class="grid">
<div class="col-1-2">
<h3>
<span class="text-red" ng-if="tip.isNew()"><b>New:</b></span>
{{ tip.title }}
<div>Category: {{ tip.getCategory() }}</div>
</h3>
</div>
<div class="col-1-2 text-right">
<span>Posted by</span>
<span class="text-blue">{{ tip.createdBy }}</span>
<span>on {{ tip.created | date:'shortDate' }}</span>
<span>{{ tip.created | date:'H:mm' }}</span>
</div>
<div class="col-1-1">
<pre>{{ tip.body }}</pre>
</div>
<div class="col-3-4">
<ul ng-if="tip.attachments.length > 0" class="attachment-list">
<li ng-repeat="attachment in tip.attachments">
{{ attachment.name }}
</li>
</ul>
<div class="col-1-1">
</div>
<div class="col-1-1">
Angular Add Comment
<button onclick="addComment();" id="addcomment/{{tip.id}}" class="btn-yellow">Add Comment</button>
</div>
</div>
<!---->
<div class="col-1-4 text-right" ng-if="tip.createdBy == user.ntid">
<a href="#/tips/edit/{{ tip.id }}?paginatePage={{ params.paginatePage }}" class="btn-yellow" >Edit</a>
<!--Delete0-->
<button ng-ask="deleteTip(tip)" title="Delete"></button>
</div>
</div>
</div>
<div style="margin-top: 20px">
<div paginate-controller></div>
</div>
</div>
</div>
I call in the code the addComment() function ( I tried jquery first )
<script>
function addComment() {
console.log('in');
}
</script>
Try moving the function out of the markup and into the controller...
...inside TipsCtrl...
$scope.addComment = function() {
console.log('in');
};

Categories