Remove Item From Array after ajax response - ajax

I'm a frustrated Vue.js noobie coming from jQuery.
I'm trying to do something very basic for a simple project: Delete an article but only after ajax response. While waiting, for the response there's a spinner. (I don't want components or vue files. It's a simple, single file app)
I've been hacking away at it for a few days now and I can't grasp some basic concepts it seems. (Or I want it to behave like jquery)
Fiddle
window.app = new Vue({
el: '#app',
data: {
name: '',
posts: [],
loadingItems: [],
},
created() {
this.fetchData();
},
methods:{
fetchData() {
axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {
this.posts = response.data.slice(0,20);
});
},
removeItem(item) {
var index = this.posts.indexOf(item);
//var loadingIndex = this.loadingItems.push(item) - 1;
//console.log(loadingIndex);
item.isLoading = true;
//Update vue array on the fly hack - https://vuejs.org/2016/02/06/common-gotchas/
this.posts.splice(index, 1,item);
axios.post('//jsfiddle.net/echo/json/', "json='{status:success}'&delay=2")
.then(response => {
this.posts.splice(index, 1);
//this.loadingItems.splice(loadingIndex, 1);
//this.loadingItems.pop(item);
//item.isLoading = false;
//this.posts.splice(index, 1,item);
});
}
},
computed: {
showAlert() {
return this.name.length > 4 ? true : false
}
}
})
<div id="app">
<div v-for="(post,index) in posts" :key="post.id">
<b-card class="mb-2">
<b-card-title>{{post.title}}</b-card-title>
<b-card-text>{{post.body}}</b-card-text>
<a href="#" #click.prevent="removeItem(post)" class="card-link">
Remove
<span v-show="post.isLoading" class="spinner"></span>
</a>
</b-card>
</div>
</div>
Works fine for deleting them 1 by 1 one but not when you click on multiple at the same time, since the index is different by the time the request comes back and it splices the wrong item.
What I've tried so far:
First, it took me a day to figure out that item.isLoading = true; won't work if it wasn't present when the data was first observed (or fetched). However, I don't want to add the property to the database just for a loading animation. So the workaround was to do this.posts.splice(index, 1,item); to "force" Vue to notice my change. Already feels hacky.
Also tried using an array LoadingItems and pushing them while waiting. Didn't work due to the same problem: don't know which one to remove based on index alone.
Studying the TODO app didn't help since it's not quite addressing handling async ajax responses or adding properties at runtime.
Is the best way to do it by using post.id and then trying to pass it and find it back in the array? Really confused and thinking jQuery would have been easier.
Any help will be appreciated. Thanks!

Works fine for deleting them 1 by 1 one but not when you click on multiple at the same time, since the index is different by the time the request comes back and it splices the wrong item.
Don't save the index in a variable. Calculate it every time you need it:
removeItem(item) {
item.isLoading = true;
this.posts.splice(this.posts.indexOf(item), 1, item);
axios.post('/echo/json/', "json='{status:success}'&delay=2")
.then(response => {
this.posts.splice(this.posts.indexOf(item), 1);
});
}

Related

Laravel and vue infinite loader and pagination problem

My project:
I have many posts, the index method returns paginated posts, 3 per page.
However in my Vuejs i don't want to show pages and i use infinite scrolling to show next 3 posts every time user scrolls to bottom of the page.
Everytime i remove a post i manage to remove it in realtime with vue. Page won't get refreshed and the post gets deleted in realtime.
The problem:
When i load posts in frontend, i have 3 posts loaded, then i remove a post for example post #1.
As we know second page in laravel means escape first 3 posts and get the second set
of 3 posts.
Now with the first post removed from database, when i go to bottom of page im expecting to get posts #4 #5 #6, but i will get #5 #6 #7.
reason:
because one post is gone in database and the next set of 3 posts are different now.
But how to solve this?
is there a solution for this problem
Well I think best solution is to update the array of Posts after every delete request. Simply make GET request with current page right after delete operation and update the array and add new value to existing array, if any. Now I have written a sample code for it I hope it will help.
Since you didn't share code so possible Code for your Component
<template>
<div>
<div v-for="post in posts" :key="post._id">
<div>{{post.name}}</div>
<div>
<button #click="deletePost(post)">Delete</button>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default() {
data() {
current_page: 1,
posts: []
},
created() {
this.updatePosts();
},
methods: {
updatePosts() {
axios.get("http://www.example.com/posts"{
params: {page: this.current_page}
}).then(res => {
if(res.status == '200') {
res.data.posts.forEach(post => {
if(!this.posts.includes(post)) this.posts.push(post);
});
}
}).catch(err => console.log(err));
},
deletePost(post) {
axios.delete("http://www.example.com/posts",{
params: {id: post.id}
}).then(res => {
if(res.status == '200') {
this.updatePosts(); // this will update array
}
}).catch(err => console.log(err));
}
}
}
</script>
Remember to increase current_page value by 1 when hit bottom of page.

Subscription reactive on Session changes causes #each to redraw every entity

So here's the catch: I store the user's coordinates using this neat solution. Here is my implementation:
updateLoc = function () {
var position = Geolocation.latLng() || {lat:0,lng:0};
Session.set('lat', position.lat);
Session.set('lon', position.lng);
};
Meteor.startup(function() {
updateLoc(); // set at 0, 0 to begin with
Meteor.setTimeout(updateLoc, 1000); // get first coordinates 1 second in
Meteor.setInterval(updateLoc, 5000); // then, every 5 seconds
});
I have an entitiesList route waiting on entities to be subscribed, according to those two session variables:
this.route('entitiesList', {
path: '/',
waitOn: function() {
if (Meteor.userId())
return Meteor.subscribe('entities', {lat: Session.get('lat'),lon: Session.get('lon')});
},
data: function() {
return {entities: Entities.find()};
}
});
Here is the publication:
Meteor.publish('entities', function (position) {
if (position.lon !== null && position.lat !== null) {
return Entities.find({location: {
$near: {$geometry:{type: "Point", coordinates: [position.lon, position.lat]},$maxDistance:500}}
}});
}
this.ready();
});
Finally, the entitiesList template :
<template name="entitiesList">
<div class="entities">
<h1>Entities list</h1>
{{#each entities}}
{{> entityItem}}
{{else}}
<p>No entity found. Looking up...</p>
{{>spinner}}
{{/each}}
</div>
</template>
Now! This solution works. Entities are listed correctly, updated every 5 seconds according to the user's location.
The only issue lies in rendering: when the reactivity is due to an update of Session variables, the entire set of entities is deleted and redrawn. But when a change occurs in the Entity Collection (say, an entity gets deleted / created) only this change is re-rendered accordingly in the template.
What this produces is a list that flashes very annoyingly every 5 seconds. I thought of removing the #each block and sort of write it myself using this.autorun() in the rendered function of the template, and to redraw the list in a more optimized fashion using jQuery, but it would be an obnoxious hack, with HTML chunks of code outside of the template files... Surely there's gotta be another way!
Each time you change your session variables, your subscription is loading and Iron Router sets his loading template and that's why it's flickering.
Instead of using iron-router you could do:
Template.entitiesList.created=function()
{
var self=this
this.isLoading=new ReactiveVar(false)
this.isFirstLoading=new ReactiveVar(true)
this.autorun(function(){
self.isLoading.set(true)
Meteor.subscribe('entities', {lat: Session.get('lat'),lon: Session.get('lon')},function(err){
self.isLoading.set(false)
self.isFirstLoading.set(false)
});
})
}
Template.entitiesList.helpers({
entities:function(){return Entities.find()}
isLoading:function(){Template.instance().isLoading.get()
isFirstLoading:function(){Template.instance().isFirstLoading.get()
})
<template name="entitiesList">
<div class="entities">
<h1>Entities list</h1>
{{#if isFirstLoading}}
<p>Looking up...<p/>
{{>spinner}}
{{else}}
{{#each entities}}
{{> entityItem}}
{{else}}
<p>No entity found</p>
{{/each}}
{{#if isLoading}}
{{>spinner}}
{{/if}}
{{/if}}
</div>
</template>
Fiddling through with iron-router, I found that there actually is an option to not render the loading template on every new subscription triggered: the subscriptions option. Just had to replace waitOn by subscriptions and I get the desired result.

How to initialize select2 that uses a query for data when I already have a value

I have a view with 2 select boxes which are "cascading". A user selects a value from the first box and the second is populated based on the new value. This is done with Select2's query option, and works fine on the first load of the page. However, when I post the page and then render it, both select boxes already have values (say A and 1), but the dependent checkbox is not initialized. I have done a few things with initSelection and it didn't help much, sometimes just getting me into an loop.
What I am trying to do is this:
Link the two boxes
When the first box changes, reset the data in the second box and clear the value
When the page is re-drawn, and a value has already been selected (e.g. response to POST)
Go to server and get the data
Show the correct value for the existing <input type='hidden' value='xxx'>
if that value exists in the list, of course
if not, set value to blank (optionally fire jquery validation
Searching/constant querying is not needed. Just load once on change
I am thinking about changing this entire, so if this is really the wrong way to go about this, I'd be happy to know.
// caches ajax result based on `data`
// if data has been requested before, retrieves from the cache (nothing special)
// based on other code that did it all inside the `query` function directly
var locationsCache = new AjaxCacheClassThing( {
url: '...',
data: function() { return { masterId: $('#ParentBox').val(); } }
});
$(function() {
$('#ParentBox').change(function () {
$('#ChildBox').select2('data', null);
});
$('#ChildBox').select2({
query: locationsCache.queryCallbackHandler,
selectOnBlur: true,
});
});
The HTML uses the standard MVC helpers, and the HTML is rendered just fine.
#Html.DropDownListFor(m => m.ParentBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.ChildBox)
Here is how this scenario goes:
ParentBox is required (no empty option)
First Load: there is no value selected
Open the DependentBox
Ajax query issues correctly
Dropdown populates as expected
Second Load
Master box selects value just fine
ChildBox hidden input has value="xx" just fine
It does not show a selected item
Clicking dropdown populates the box as expected (from cache)
After some time spent, and lots of time on here and other places, I figured out how this all works (at least some parts of it!). Way simpler than I thought it was, but still surprised this isn't supported out of the box in some way. Seems like a really common request.
query and ajax and initselection aren't that useful in this scenario
They query each time a the search box changes (not desired)
They complicate everything
You need to init the select2 manually
If you use { data: ... } then you don't need query or ajax
Set the "value" on your hidden input if you have one, so the item gets selected
You have to recreate the box when you get new data
It is really simple. This is the simplest case, using no extra features or attributes
Javascript:
$(function() {
$('#ParentBox').change(createChildSelect2);
createChildSelect2();
});
function createChildSelect2() {
makeAjaxRequest( function( newData ) {
$('#ChildBox').select2( { data: newData } );
});
}
function makeAjaxRequest(callback) {
// calls a.jsp?parentId={?} and then the callback when done.
jQuery.ajax({
url: 'a.jsp', dataType: 'json',
data: function() {
return { parentId: $("#parentBox").val() };
}
})
.done(function (data) {
callback(data);
});
}
The HTML is all the same. A type=text and type=hidden both work:
<select id="ParentBox">
<option ... >
<option ... >
<select>
<input id="ChildBox" type="hidden" class="input-medium" value="1"/>
Or using Razor:
#Html.DropDownListFor(m => m.MasterBox, SelectListOfStuff) // standard <select>
#Html.HiddenFor(m => m.DependentBox)

twitter bootstrap dynamic carousel

I'd like to use bootstrap's carousel to dynamically scroll through content (for example, search results). So, I don't know how many pages of content there will be, and I don't want to fetch a subsequent page unless the user clicks on the next button.
I looked at this question: Carousel with dynamic content, but I don't think the answer applies because it appears to suggest loading all content (images in that case) from a DB server side and returns everything as static content.
My best guess is to intercept the click event on the button press, make the ajax call for the next page of search results, dynamically update the page when the ajax call returns, then generate a slide event for the carousel. But none of this is really discussed or documented on the bootstrap pages. Any ideas welcome.
If you (or anyone else) is still looking for a solution on this, I will share the solution I discovered for loading content via AJAX into the Bootstrap Carousel..
The solution turned out to be a little tricky since there is no way to easily determine the current slide of the carousel. With some data attributes I was able to handle the .slid event (as you suggested) and then load content from another url using jQuery $.load()..
$('#myCarousel').carousel({
interval:false // remove interval for manual sliding
});
// when the carousel slides, load the ajax content
$('#myCarousel').on('slid', function (e) {
// get index of currently active item
var idx = $('#myCarousel .item.active').index();
var url = $('.item.active').data('url');
// ajax load from data-url
$('.item').html("wait...");
$('.item').load(url,function(result){
$('#myCarousel').carousel(idx);
});
});
// load first slide
$('[data-slide-number=0]').load($('[data-slide-number=0]').data('url'),function(result){
$('#myCarousel').carousel(0);
});
Demo on Bootply
I combined #Zim's answer with Bootstrap 4. I hope it will help someone.
First, load just the path of the images:
<div id="carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item" data-url="/image/1.png"></div>
<div class="carousel-item" data-url="/image/2.png"></div>
<div class="carousel-item" data-url="/image/3.png"></div>
</div>
</div>
Then in JavaScript:
$('document').ready(function () {
const loadCarouselImage = function ($el) {
let url = $el.data('url');
$el.html(function () {
let $img = $('<img />', {
'src': url
});
$img.addClass('d-block w-100');
return $img;
});
);
const init = function () {
let $firstCarousel = $('#carousel .carousel-item:first');
loadCarouselImage($firstCarousel);
$firstCarousel.addClass('active');
$('#productsCarousel').carousel({
interval: 5000
});
};
$('#carousel').on('slid.bs.carousel', function () {
loadCarouselImage($('#carousel .carousel-item.active'));
});
init();
});

How can i append partial view result in to div?

I have a div id="comments"
in this i am displaying 10 comments at a time.
when user want to view next comments, i have provided one button that will collect next 10 comments. for this next comment i have created partial view to display remaining 10 comments into another div morecomments.
My problem is when i am displaying next 10 comments its showing me all 20 comments but whole comments div is getting refreshed, how to prevent loading whole comment div.
My code is here:
<div id="comments">
// Display Comments
<div id="moreButton">
<input type="submit" id="more" class="morerecords" value="More Post" />
</div>
</div>
<div id="morecomments">
</div>
Jquery::
$('.morerecords').livequery("click", function (e) {
// alert("Showing more records...");
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
In above code i am getting 10 comments first time and when user click on More Post button it will show me above 10 comments plus next 10 comments. but whole div is getting refreshed.
What changes i have to do so that i can get user comments without affecting previous showing comments?
Suppose user having 50-60 post in his section then all comments should be display 10+ on More Post button click and so on...
How can i do that?
You need to filter your records and put it in comment div... Your code should like this:
$('.morerecords').livequery("click", function (e) {
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
var older_records = $("#morecomments").text();
$.("comments").append(older_records); //When you will get next record data, older data will be filled in comment div.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
The error is in:
$("#morecomments").html(result);
.html("somevalue") deletes the content, then fills it with whatever parameter you supplied.
Try doing this:
$("#morecomments").html($("#morecomments").html() + result);
or even easier:
$("#morecomments").append(result);
I know this works if you're passing strings, and a partial view is basically a html string. I don't know if there will be any conflict issues with the tags brought along by partial views.
Either way, this is the easiest way to add to an element rather than write over it.
If you are using Entity Framework (which you do), you need to use something like below:
public JsonResult Get(
//this is basically giving how many times you get the comments before
//for example, if you get only one portion of the comments, this should be 1
//if this is the first time, this should be 0
int pageIndex,
//how many entiries you are getting
int pageSize) {
IEnumerable<Foo> list = _context.Foos;
list.Skip(PageIndex * PageSize).Take(pageSize);
if(list.Count() < 1) {
//do something here, there is no source
}
return Json(list);
}
This is returning Json though but you will get the idea. you can modify this based on your needs.
You can use this way for pagination as well. Here is a helper for that:
https://bitbucket.org/tugberk/tugberkug.mvc/src/69ef9e1f1670/TugberkUg.MVC/Helpers/PaginatedList.cs

Resources