Jquery ajax click function wont work - javascript

I am trying to make a ajax click to load div function. But the click function doesn't work. What i am doing wrong here? Anyone can help me in this regard ?
DEMO from Jsfiddle
var response = '<div class="icon_b">
<div class="clickficon"></div>
<div class="emicon-menu MaterialTabs">
<ul>
<li class="tab active"> Starks</li>
<li class="tab"> Lannisters</li>
<li class="tab"> Targaryens<span></span></li>
</ul>
<div class="panels">
<div id="starks-panel1" class="panel pactive"> a </div>
<div id="lannisters-panel1" class="panel"> b </div>
<div id="targaryens-panel1" class="panel"> c </div>
</div>
</div>
</div>';
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
success: function (returnHtml) {
e.find('.user-container').html(returnHtml).promise().done(function () {
$('.emoticon').addClass('loaded');
});
}
});
}
function hideProfileTooltip() {
$('.the-container').removeClass('loaded');
}
$('body').on('change', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
}, function () {
hideProfileTooltip();
});
});

callback function is not valid in there,
//on load,click is more prefer than change
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
//don't call like this
//, function () {
// hideProfileTooltip();
// });

Related

After an AJAX call, my JS code doesnt load until I refresh the page

So i have a project in Laravel, I have added filters, and it filters the products fine. However, when products are filterd my add to cart buttons become unresponsive. I figured after inspecting the rendered code in the browser that the JS was not loaded. However if i manually refresh the page (or refresh in the code with location.reload()) then it works. However I want to avoid manual refresh because then I would lose the colour class added to the button to show that its active filter.
Below is the code for my product file which loads the products in a for loop from the controller:
products.blade.php
<div class="container">
<!--Grid row-->
<div class="row">
#foreach ($products as $p)
<div class="col-lg-3">
<div class="container">
<form action="{{ route('cart.add', $p->id) }}" data-id="{{ $p->id }}" id="addtocart">
<div class="row">
<h5>{{ $p -> name }}</h5>
<button type="button" id="submit" class="button has-shadow is-danger submit is-small">
Add to Cart
</button>
</div>
</form>
</div>
</div>
#endforeach
</div>
<div class="container">
{{ $products ->appends($request->query()) -> links() }}
</div>
</div>
products_show.blade.php - Where the JS is and where the above file is loaded. The issue occurs after the $('body').on('click', '.btn-filter' is called.
#extends ('layouts.app')
#section ('content')
<div class="box text-right">
<div class="row">
<button type="button" name="filter[]" value="Jackets" id="filterJackets" class="button is-info btn-filter">Jackets</button>
<button type="button" name="filter[]" value="Hoodies" id="filterHoodies" class="button is-info btn-filter">Hoodies</button>
</div>
</div>
<section class="products">
#include('product.products')
</section>
#endsection
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document)
.ajaxStart(function () {
$("#modal").show();
})
.ajaxStop(function () {
$("#modal").hide();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Pagination
$('body').on('click', '.pagination a', function(e) {
var url = $(this).attr('href');
$.ajax({
url : url
}).done(function (data) {
$('.products').html(data);
}).fail(function () {
alert('Products could not be loaded.');
});
window.history.pushState("", "", url);
});
// Add to cart
$(".submit").click(function (e) {
e.preventDefault();
var p_id = $(this).closest("form").data('id');
var product_id = $("#product_id").val();
var url = $(this).closest('form').attr('action');
$.ajax({
url:url,
method:'POST',
data:{
product_id:product_id
},
success:function(response){
console.log("added to cart success");
},
});
});
$('body').off('click', '.btn-filter', function(e) {
$(this).removeClass("is-success");
});
$(".btn-filter").hover(function(){
$(this).addClass("is-danger");
}, function(){
$(this).removeClass("is-danger");
});
var filters = [];
$('body').on('click', '.btn-filter', function(e) {
e.preventDefault();
$(this).toggleClass('is-success');
filters = []; // reset
$('button[name="filter[]"]').each(function()
{
if ($(this).hasClass("is-success")) {
filters.push($(this).val());
}
});
var url = '{{ route('products.type') }}'+'?filter[storage]='+filters
$.ajax({
url : url
}).done(function (data) {
$('.products').html(data);
}).fail(function () {
alert('Products could not be loaded.');
});
window.history.pushState("", "", url);
});
});
</script>
I am not sure if the php code matters because the problem here is the add to cart button JS is not being called, but here it is anyways:
public function filterByType(Request $request){
$products = QueryBuilder::for(Auth::user()->products())
->allowedFilters(['type'])->paginate()
->appends(request()->query());
// Check if request is from ajax
if ($request->ajax()) {
return view('product.products', ['products' => $products])->render();
}
return view('product.products_show', compact('products'));
}
Thanks.
So i found a hackway to do this, However is there a better solution or a way to fix my issue? And is what i did here bad?:
I added location.reload() to the end of the btn-filter on click which will reload the page since reloading the page fixes the issue for me.
I then added the code below to the top of the script:
var window_url = window.location.href;
var url_filter_params = window_url.substr(window_url.indexOf("=") + 1)
var filter_params_array = url_filter_params.split(',');
$('button[name="filter[]"]').each(function()
{
if ($.inArray($(this).val(), filter_params_array) >= 0){
$(this).addClass('is-success');
}
});
This basically gets the URL parses it to get the params, and then shows adds the is-warning class back to the button to make it appear as selected. The filters also work.

How to override a javascript function (written in a .cshtml file ) into a separate .js file

This is my function in .cshtml file and I want to override this function in my new .js file so that whatever code I write in the .js file in this function should get executed and not what is written in the .cshtml file.
$("#assoc-search-popup").kendoButton({
enable: true,
click: function(e) {
$.ajax({
cache: false,
type: "POST",
url: "/Search/AssocLookup",
data: {
"lookupEntityName": lookupEntityName
},
success: function(data) {
var lookup_popup = $("#lookup_popup_content");
lookup_popup.html("");
lookup_popup.html(data);
$('.searchbar-toggle').click(function(e) {
toggleFilterPane();
if ($("#divButtons").hasClass("search-popup-btn_expand")) {
$("#divButtons").removeClass("search-popup-btn_expand");
$("#divButtons").addClass("search-popup-btm_collapse");
} else if ($("#divButtons").hasClass("search-popup-btm_collapse")) {
$("#divButtons").removeClass("search-popup-btm_collapse");
$("#divButtons").addClass("search-popup-btn_expand");
}
});
$("#btnSelectItem").attr("search-lookup-type", "inheritance");
ifPopup("lookup_popup");
}
});
});
});
<a id="assoc-search-popup1" style="display: inline-block;"
href="javascript:void(0)" class="associate-and-inherit-link"
data-associatedentityname="Logistics"
data-associatedentityid="1E74AF39-6B99-4685-9C3F-5F47DB47A410"
data-associationname="Logistics"
data- associatedmultiplicity="Many"
data-inheritancepriority="2"
data-associatedentitydisplayname="Logistics"
data-hasviewpermission="true"
data-metadata_display_name="Logistics"
data-metadata_display_name_plaintext="Logistics"
data-islookup="true"
data_lookupentityname="Logistics">
<span>Logistics</span>
<span class="inherit_details_add" style="float: right !important;"></span>
</a>
The fastest is to do this after load and after the other script:
Note the $clone.on() code will be $clone.kendoButton() in your case
$(function() { // after page load
let $link = $("#assoc-search-popup1");
let $clone = $link.clone(false, false); // without event handlers
$clone.on("click", function() {
alert("replaced event handler");
});
$link.replaceWith($clone);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<a id="assoc-search-popup1" style="display: inline-block;" href="javascript:void(0)" class="associate-and-inherit-link" data-associatedentityname="Logistics" data-associatedentityid="1E74AF39-6B99-4685-9C3F-5F47DB47A410" data-associationname="Logistics"
data- associatedmultiplicity="Many" data-inheritancepriority="2" data-associatedentitydisplayname="Logistics" data-hasviewpermission="true" data-metadata_display_name="Logistics" data-metadata_display_name_plaintext="Logistics" data-islookup="true"
data_lookupentityname="Logistics">
<span>Logistics</span>
<span class="inherit_details_add" style="float: right !important;"></span>
</a>
<script>
$("#assoc-search-popup1").on("click", function() {
alert("event handler to be replaced"); // your initial kendo button
});
</script>
</div>

jQuery drag-drop working for files, but not folders

I'm using the jquery and jquery UI plugin to drag and drop elements (folders and files) just like in a filebrowser.
I can manage to have the file go 'into' the folder, but not a folder to go into another.
Here is a demo :
There seems to be something conflicting, but I don't know where to look anymore.
The javascript is like this :
$(function () {
// fancytree is part of another script
$("#tree").fancytree({
expandLazy: true,
activate: function (event, data) {
var node = data.node;
if (node.data.href) {
window.open(node.data.href, node.data.target);
}
}
});
/* DRAG AND DROP STARTS HERE */
$(".listitems").draggable();
$(".droppable").droppable({
//preventCollision: true,
drop: function (event, ui) {
var draggableId = ui.draggable.attr("id");
var droppableId = $(this).attr("id");
//alert('FILE'+draggableId+' DROPED INTO '+droppableId);
$(this).append(ui.draggable);
var itemid = ui.draggable.attr('data-itemid');
var folderid = ui.draggable.attr('data-fldmid');
if (typeof folderid == 'undefined') {
folderid = 0;
}
if (typeof itemid == 'undefined') {
itemid = 0;
}
if (typeof droppableId == 'undefined') {
droppableId = 0;
}
$.ajax({
method: "POST",
url: "_ajax/filemanager/dragdrop.php",
//data : 'FileID='+ itemid +'&FolderID='+ droppableId,
data: 'FileID=' + itemid + '&FolderID=' + folderid + '&DropID=' + droppableId,
}).done(function (data) {
var result = $.parseJSON(data);
if (folderid == 0) {
//alert('FILE MOVED - FileID='+ itemid +'&FolderID='+ folderid+'&DropID='+ droppableId);
// Done moving file, hiding it
$("div#" + itemid).hide(500);
} else {
//alert('FOLDER MOVED - FileID='+ itemid +'&FolderID='+ folderid+'&DropID='+ droppableId);
// Done moving directory, hiding it
$("div#" + folderid).hide(500);
}
//$("div#"+folderid).hide(500);
//$("div#"+droppableId).hide(500);
});
}
});
$(".listitems").sortable();
$(".listitems").disableSelection();
var shouldCancel = false;
$('.dragMe').draggable({
containment: '.moveInHere',
revert: function () {
if (shouldCancel) {
shouldCancel = false;
return true;
} else {
return false;
}
}
});
$('.butNotHere').droppable({
over: function () {
shouldCancel = true;
},
out: function () {
shouldCancel = false;
}
});
});
And here is the html
<div class="box-body">
<div class="table-responsive mailbox-messages moveInHere" style="overflow: hidden; min-height:600px;">
<p>
<!--id, data-fldmid and data-itemid were added for testing purposes -->
<div class="boxFile small droppable listitems dragMe drag" id="D.4" data-fldmid='D.4' data-itemid='4'>
<a href="?n=9">
<div class="ffolder small yellow"></div>
</a>
<div class="boxFileTitle">Folder 1 (4)</div>
</div>
<div class="boxFile small droppable listitems dragMe drag" id="D.7" data-fldmid='D.7' data-itemid='7'>
<a href="?n=7">
<div class="ffolder small yellow"></div>
</a>
<div class="boxFileTitle">Folder A (7)</div>
</div>
<p>
<div style="" class="boxFile small listitems butNotHere dragMe drag" id="26" data-itemid='26'>
<img src='image.php?id=26' class='UploadedImageThumb'>
<div class="boxFileTitle">2016-12-12 14.50.14.jpg26</div>
<div class="boxFileOption">Preview | Edit | Trash</div>
</div>
</p>
<p>
<div style="" class="boxFile small listitems butNotHere dragMe drag" id="25" data-itemid='25'>
<img src='image.php?id=25' class='UploadedImageThumb'>
<div class="boxFileTitle">test.jpg25</div>
<div class="boxFileOption">Preview | Edit | Trash</div>
</div>
</p>
</p>
</div>
</div>
The 'butNotHere' class is to prevent files to be on top of each other. All this works fine, except the folder-into-folder dragging as described above.
I found the error, the variable in JS (folderid) had a letter 'D' in front of the real id. I did this during test to check if it was a file being moved or folder. So 'F' or 'D'.
So I changed this line
data-fldmid='D.7'
To this and it worked
data-fldmid='7'

how to get the inside id using jquery?

I want to assign values to inside id how can i do that in Jquery
controller.cs code
public GroupModel Get()
{
IGroupTypeRepository groupTypeRepo = new GroupTypeRepository();
IGroupRepository groupRepo = new GroupRepository();
var model = new GroupModel();
model.GroupTypes = groupTypeRepo.GetAll().ToList();
Guid first = model.GroupTypes.FirstOrDefault().Id;
model.Groups = groupRepo.GetAll().Where(s => s.Type == first).ToList();
return model;
}
I tried like following
function getGroups() {
debugger;
$.getJSON(
"groupvalues",
function (data) {
if (data.GroupTypes != undefined) {
$.each(data.Groups, function (jindex, jvalue) {
debugger;
if (jvalue.Id != undefined) {
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
}
});
}
}
<div class="span9">
<div class="row">
<section id="projects">
</section>
</div>
</div>
<script id="GroupsTemplate" type="text/html">
<ul id="thumbs">
<li class="item-thumbs span3 Dhol">
<span class="font-icon-music"></span>${GroupType.TypeName}<br />
</p></div> </li>
</ul>
</script>
I guess i'm going wrong here in js function
$("#GroupsTemplate").tmpl(jvalue).appendTo(".span9 .row #projects");
I think that instead of this:
${GroupType.TypeName}
you must have only this:
${TypeName}
because the GroupType is the parameter object for the template (implicit).
Hope this helps. Cheers

Retrieve Class element from Div

I am using the autodividersSelector function to display post date as divider text. I am stuck at the point of how to navigate to retrieve the date class. Below is the code and console log of the Div element in DOM.
If this question had been answered else where, please provide me with the link. Thanks
Code
$(document).on('pagebeforeshow', '#blogposts', function () {
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" ,
dataType: "json" ,
beforeSend: function () {$('.loader').show();},
complete: function () {$('.loader').hide();},
success: function (data){
$('#postlist').empty();
//setTimeout(function(){
$.each(data.posts, function (key, val) {
//Format date
var dateString = val.date.split(' ')[0];
var vdate = dateString.split("-")[1] + " " + monthStrings[parseInt(dateString.split("-")[1])] + ", " + dateString.split("-")[0];
//Output data collected into page content
var rtitle = $('<p/>', {'class' : 'vTitle', html: val.title}); rdate = $('<p/>', {'class': 'vDate' , html: vdate});
rid = $('');
var rappend = $('<li/>').append(rtitle, rdate);
$('#postlist').append($(rappend).wrapInner(rid).fadeIn(600));
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
//console.log(li);
var out = $(li).get(0)
console.log(out);
return out;
}
});
return (key !== 5);
});
$("#postlist").listview().listview('refresh').append('<div class="more-posts" style="text-align: center;">Load more posts...</div>');
// }, 2000);
},
error: function (data) {
alert("Service currently not available, please try again later...");
}
});
});
Result of output showing [objectHTMLLiElement] in the divider
HTML:
<!-- Page: Blog Posts -->
<div id="blogposts" data-role="page">
<div data-role="header" data-position="fixed">
<h2>My Blog Posts</h2>
</div><!-- header -->
<div data-role="listview">
<ul data-filter="true" data-filter-placeholder='Search blog posts...' data-theme="a" id="postlist"> </ul><!-- content -->
</div>
<div class="loader"><img src="css/images/loader.gif"/></div>
</div><!-- page -->
$('.vDate').each(
function(){
alert($(this).html());
}
);
OK this is the final code that worked for custom autodividersSelector:
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.find("p").map(function() {return $(this).text();});
var out1 = out.get(1);
return out1;
}
});

Categories

Resources