Scripts not working on partial view after Ajax call - ajax

I have called scripts on _Layout.cshtml page and my Index.cshtml page has partial view into it. So on page load, SignalR scripts working perfect on partial view, on page end I make another ajax request and load the partial view with another data filled in that and embed under already displayed data, and then the SignalR does not work on the newly embedded record.
This is my index page code:
<div class="col-md-6">
<div class="profile-body">
<div class="row infinite-scroll">
#Html.Partial("_AlbumRow", Model)
</div>
</div>
</div>
This is my partial View Code:
#model IEnumerable<SmartKids.Lib.Core.ViewModels.FileMediaAlbumsVM>
#foreach (var item in Model)
{
<div class="widget">
<div class="block rounded">
<img src="#Url.Content(item.ImageUrl)" alt="#item.Title">
<input type="button" data-image-id="#item.imageId" class="btn btn-sm btn-default">Like</input>
</div>
</div>
}
Kindly help me how to resolve this issue that after making an ajax request I am not able to get those SignalR working. Here is more to say when I put the SignalR scripts on PartialView that works but it also sucks that on each ajax request there is again SignalR loaded on the page and when I click on LIke button it makes many calls to the function behind it.
Kindly help me to resolve this issue, I am stuck at this point since 1 week.
Here is signalR Code:
$(".btn.btn-sm.btn-default").on("click", function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(imageId);
});

Problem: You are binding event to elements directly, So when you remove this element and replace it with a different one the events are also removed along with that element, This is something like strongly coupled.
Solution: Use Jquery event delegation. This will make sure the events will be triggered on the current elements and also all the elements that can come in future.
syntax is as below.
$(document).on("click", ".btn.btn-sm.btn-default",function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(iamgeId);
});
NOTE: This was never a singlaR issue, it was Jquery issue.
Efficient Way: The problem in using $(document).on("click"... is that when ever there is a click happening on the entire page the Jquery framework will bubble the events from the clicked element upwards(its parent, and its parent and so on..) unless the element specified in the selector arrives, So its kind of performance hit as we don't want this check's to run if we are clicking outside the required area ( button .btn.btn-sm.btn-default in this example).
So best practice is to bind this event delegation to the closest parent possible which will not be removed, <div class="row infinite-scroll"> in this question. So that only when the click happens within this element the event bubbling will happen and also will be stopped once it reaches the parent element,it acts kind of a boundary for event bubbling.
$('.row.infinite-scroll').on("click", ".btn.btn-sm.btn-default",function () {
var imageId = $(this).attr("data-image-id");
albumClient.server.like(iamgeId);
});

Related

Laravel Livewire/AlpineJS: Disable a button while loading data from an API and then enabling it again

This should be really simple, but I don't get it. I want to replicate the functionality of a button that when pressed goes to an API (which could take about a minute to get the data and process it), it gets diabled, and after loading the data it gets enabled.
I'm using Laravel/Livewire/Alpine
So, in my livewire component I have:
public $loading = false;
In my blade file, I have the declaration for the div where the button is:
<div
class="grid grid-cols-3 gap-4"
x-data="{
loading: #entangle('loading')
}"
>
Then the button x-binds the disabled property to the loading value, when the button is clicked, it changes the property of the loading variable, and calls the loader function
<button
type="button"
class="btn btn-sm btn-jbn"
x-on:click="loading = true"
x-bind:disabled="loading"
wire:click="loader"
>
Load API
</button>
And it does what it is supposed to do... the button is grayed, it becomes unusable, the cursor change, etc., it executes the loader function in my livewire component, but it never return to the normal state after loading the API. In my livewiere componente I have:
public function loader() {
// API call and logic goes here, this works
$this->loading = false;
}
So I would imagine that at the end of the API process the entangled variable loading would return the button to its normal state, but it doesn't
What am I missing?
Livewire already has incorporated functionality to handle loading-states. Instead of implementing your own, you can use this.
Get rid of all your current loading-logic, and simply use wire:loading with wire:target on your button.
wire:loading can toggle the disabled attribute directly by doing wire:loading.attr="disabled", and wire:target is to set the target for that loading-state to the method you are calling, so in your case that's wire:target="loader".
This means your button looks like this,
<button
type="button"
class="btn btn-sm btn-jbn"
wire:click="loader"
wire:loading.attr="disabled"
wire:target="loader"
>
Load API
</button>

Mixing Alpine.js with 'static' serverside markup, while getting the benefits of binding, etc

I'm new to Alpine and struggling to wrap my head around how to make a scenario like this work:
Let's say I have a serverside built page, that contains some buttons, that represent newsletters, the user can sign up to.
The user might have signed up to some, and we need to indicate that as well, by adding a css-class, .i.e is-signed-up.
The initial serverside markup could be something like this:
<button id='newsletter-1' class='newsletter-signup'>Newsletter 1</button>
<div>some content here...</div>
<button id='newsletter-2' class='newsletter-signup'>Newsletter 2</button>
<div>more content here...</div>
<button id='newsletter-3' class='newsletter-signup'>Newsletter 3</button>
<div>and here...</div>
<button id='newsletter-4' class='newsletter-signup'>Newsletter 4</button>
(When all has loaded, the <button>'s should later allow the user to subscribe or unsubscribe to a newsletter directly, by clicking on one of the buttons, which should toggle the is-signed-up css-class accordingly.)
Anyway, then I fetch some json from an endpoint, that could look like this:
{"newsletters":[
{"newsletter":"newsletter-1"},
{"newsletter":"newsletter-2"},
{"newsletter":"newsletter-4"}
]}
I guess it could look something like this also:
{"newsletters":["newsletter-1", "newsletter-2", "newsletter-4"]}
Or some other structure, but the situation would be, that the user have signed up to newsletter 1, 2 and 4, but not newsletter 3, and we don't know that, until we get the JSON from the endpoint.
(But maybe the first variation is easier to map to a model, I guess...)
Anyway, I would like to do three things:
Make Alpine get the relation between the model and the dom elements with the specific newsletter id (i.e. 'newsletter-2') - even if that exact id doesn't exist in the model.
If the user has signed up to a newsletter, add the is-signed-up css-class to the corresponding <button> to show its status to the user.
Bind to each newsletter-button, so all of them – not just the ones, the user has signed up to – listens for a 'click' and update the model accordingly.
I have a notion, that I might need to 'prepare' each newsletter-button beforehand with some Alpine-attributes, like 'x-model='newsletter-2', but I'm still unsure how to bind them together when Alpine has initialising, and I have the data from the endpoint,
How do I go about something like this?
Many thanks in advance! 😊
So our basic task here is to add/remove a specific item to/from a list on a button click. Here I defined two component: the newsletter component using Alpine.data() creates the data (subs array), provides the toggling method (toggle_subscription(which)) and the checking method (is_subscribed(which)) that we can use to set the correct CSS class to a button. It also handles the data fetching in the init() method that executes automatically after the component is initialized. I have also created a save method that we can use to send the subscription list back to the backend.
The second component, subButton with Alpine.bind() is just to make the HTML code more compact and readable. (We can put each attribute from this directly to the buttons.) So on click event it calls the toggle_subscription with the current newsletter's key as the argument to add/remove it. Additionally it binds the bg-red CSS class to the button if the current newsletter is in the list. For that we use the is_subscribed method defined in our main component.
.bg-red {
background-color: Tomato;
}
<script src="https://unpkg.com/alpinejs#3.x.x/dist/cdn.min.js" defer></script>
<div x-data="newsletter">
<button x-bind="subButton('newsletter-1')">Newsletter 1</button>
<button x-bind="subButton('newsletter-2')">Newsletter 2</button>
<button x-bind="subButton('newsletter-3')">Newsletter 3</button>
<button x-bind="subButton('newsletter-4')">Newsletter 4</button>
<div>
<button #click="save">Save</button>
</div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('newsletter', () => ({
subs: [],
init() {
// Fetch list of subscribed newsletters from backend
this.subs = ['newsletter-1', 'newsletter-2', 'newsletter-4']
},
toggle_subscription(which) {
if (this.subs.includes(which)) {
this.subs = this.subs.filter(item => item !== which)
}
else {
this.subs.push(which)
}
},
is_subscribed(which) {
return this.subs.includes(which)
},
save() {
// Send this.sub to the backend to save active state.
}
}))
Alpine.bind('subButton', (key) => ({
'#click'() {
this.toggle_subscription(key)
},
':class'() {
return this.is_subscribed(key) && 'bg-red'
}
}))
})
</script>

jQuery loading items via ajax and while remove it getting notification from all previous deletion as well

I have a div like this
<section class="item_container">
<article class="item">
<h2>Page Title</h2>
<p><a class="delete_page" href="http://www.abc.com/delete/1/">delete</a></p>
</article>
<article class="item">
<h2>Second Page Title</h2>
<p><a class="delete_page" href="http://www.abc.com/delete/2/">delete</a></p>
</article>
</section>
And i am using this code to remove/delete items from item_container
$('a.delete_page').live('click', function(e){
e.preventDefault();
$('footer#ajax_footer').html('')
$('footer#ajax_footer').show("slide", { direction: "down" }, 500);
var url = $(this).attr("href");
var parent_div = $(this).parents("div").parent("article");
var title = $(this).parents("div").parent("article").find('h2').html();
$('footer#ajax_footer').html('<h2>Are you sure you want to delete <u>'+ title +'</u> Page</h2><p>'+ url +'</p><p>Yes, Please Delete It</p>');
$('a.delete_this_page').live('click', function(e){
e.preventDefault();
parent_div.remove();
$('footer#ajax_footer').html('').slideUp();
$.sticky('<b>Page Deleted</b><p><u>'+ title +'</u> Page has been successfully deleted.</p>');
});
});
All the contents are loaded via Ajax and there are few more div in each article and there are 30+ articles.
The problem is i am using Sticky plugin to display notification after every item is deleted and it's working fine, Everything is working fine, But after i delete an Article, The sticky notification of previous deletion is displayed as well.
Like, After i delete an item, i see 1 sticky notification, After i delete second item i see 2 sticky notifications (1 of this and 1 of previous) i only want to see 1, And For every item i delete it display all the previous sticky notifications + 1.
Hope i made it clear enough, Thanks guys.
The problem you have is that every time you click on a a.delete_page element you're setting up a new click event handler using .live(), so for each subsequent click you get one more event handler that gets run.
The whole point of .live() - though, as a side note, it's deprecated; consider using .on() (jQuery 1.7+) or .delegate() (prior to 1.7) - is that it handles events triggered by dynamically added elements. Call this:
$('a.delete_this_page').live('click', function(e){
e.preventDefault();
parent_div.remove();
$('footer#ajax_footer').html('').slideUp();
$.sticky('<b>Page Deleted</b><p><u>'+ title +'</u> Page has been successfully deleted.</p>');
});
outside of your other callback function (in your $(document).ready()), and find another way to identify parent_div. Or, bind the click event to that specific link directly inside the callback handler.

Create Wizard steps in MVC and Razor

I would like to build one MVC application to create the account of a user using more then one wizard steps.
Do I need to go with one view page and hide or display a div by client side logic or do I need to create different view for each wizard (using partial views)?
What is the best option here? I need to maintain state data between wizard steps so the user can move back or next and on last step he or she can save it to the database.
There are different possibilities. You could use a pure client side solution by showing/hiding sections or a full server side solution. It's up to you to decide which one is best for your particular scenario. Here's an example you might take a look at if you decide to go the server side approach.
Depends on if you allow javascript or not.
If you allow javascript, use jQuery to show/hide divs.
I just made the following wizard script. It supports multiple wizards on the same page, as long as you follow the class/div syntax below.
<div class="wizard">
<div class="step active">
some information
</div>
<div class="step" style="display:none">
Step 2 info
</div>
<div class="step" style="display:none">
Step 3 info
</div>
<input type="button" class="prev" style="display: none" value="Previous" />
<input type="button" class="next" value="Next" />
</div>
<script type="text/javascript">
$(function() {
$('.wizard .prev').click(function() {
var wizard = $(this).parent('.wizard');
$('.step.active', wizard).hide();
var currentStep = $('.step.active', wizard);
currentStep.hide();
currentStep.removeClass('active');
var newStep = currentStep.prev('.step', wizard);
newStep.addClass('active');
newStep.show();
if ($('.step:first', wizard)[0] == newStep[0]) {
$(this).hide();
}
$('.next', wizard).show();
});
$('.wizard .next').click(function() {
var wizard = $(this).parent('.wizard');
$('.step.active', wizard).hide();
var currentStep = $('.step.active', wizard);
currentStep.hide();
currentStep.removeClass('active');
var newStep = currentStep.next('.step', wizard);
newStep.addClass('active');
newStep.show();
if ($('.step:last', wizard)[0] == newStep[0]) {
$(this).hide();
}
$('.prev', wizard).show();
});
});
</script>
Without javascript:
Create a view model which contains information for all steps and share it between all wizard step views. This allows you to keep all state between the different POSTs.
I'm doing something similar at the moment. I'm collecting a large set of data over several steps and allowing the users to save the data at any point.
I've basically split it up into multiple views and created ViewModels for each view with the relevant info for that wizard step. Seems to be working reasonably well for my purposes.

JQuery for Push-down form

Is there a JQuery plugin that allows me to 'unhide' a form by after clicking a link? Like I have an invite link that can take me to a one text field form for an email address but I want this form to just drop down (pushing the rest of the content down also) and shows the form to submit the email. If you guys can think of a JQuery plugin that lets me do this, please let me know
Edit:
So I did this
<div class='add-link'>
<div id='invite_link'><a href=''>Invite User</a></div>
<div id='invitation_form'>
<form>
<input type='text'/>
</form>
</div>
</div>
and my jquery looks like
<script type="text/javascript">
$(function()
{
$("table").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']});
$('#invitation_form').hide();
}
);
$('#invite_link').click(function() {
$('#invitation_form').slideDown();
});
Do you guys see any error that causes the form not to slide down. It hides the form when the page loads but when I click the link it is not sliding down.
$('a.mylink').click(function() {
$('#MyForm').slideDown();
});
I don't think you need a jQuery plugin for this. The base jQuery library should be sufficient.
$('#showFormLink').click(function () {
$('#form').slideDown();
});
If you're looking for animation, that's possible as well by passing in a duration argument to slideDown.
Take a look at the jQuery show documentation.

Resources