Following is my function which I am using to load data as per < last id of li .post-list but still I am getting repetition of same ids that were pulled before. Kindly let me know how can I resolve this issue so the old ids doesn't load/repeat itself again.:
function loadData()
{
$('div.postloader').html('<img src="img/loader.gif">');
$.post("getData.php?lastID=" + $(".post-list:last").attr("id"),
function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
});
};
A possible soution to prevent this is to store the last ID in a global variable in JS and increment that, so you don't have to rely on selecting the right element to find the ID to POST.
you're pulling the data from the server too fast, try adding a flag that will prevent pulling the items while the request is running:
var flagPulling = false;
function loadData() {
if( flagPulling ) {
return;
}
flagPulling = true;
$('div.postloader').html('<img src="http://www.zesteve.com/img/loader.gif">');
$.post("/getData.php?lastID=" + $(".post-list:last").attr("id"), function(data){
if (data != "") {
$(".post-list:last").after(data);
}
$('div.postloader').empty();
flagPulling = false;
});
};
Related
Hopefully a quick question.
I'm using a JSON file to write out some html and populate with variables from the JSON and append it to part of my html file. This works and is fine. However, I now want to use a different script to apply show and hide filters based on class attributes to the html that has been printed. For some reason, this isn't working. If I just copy and paste the html with variables back into the original document after its been printed out, then the script works though. Is this an issues of synchronicity?
Here's the second script I'm looking to execute if it helps:
$(document).ready(function(){
var targets = $('.filter'),
buttons = $('.filter-button');
buttons.click(function(){
var value = $(this).data('filter');
if(value == "all")
{
buttons.removeClass('checked');
targets.show();
}
else
{
if($(this).hasClass('checked'))
{
$(this).removeClass('checked');
var checkedClasses = buttons.filter('.checked').toArray().map(function(btn){return $(btn).data('filter');});
if(checkedClasses.length == 0)
{
buttons.removeClass('checked');
targets.show();
}
else
{
checkedClasses = $.grep(checkedClasses, function(n, i){ return n != value }),
selector = '.' + checkedClasses.join('.'),
show = targets.filter(selector);
targets.not(show).hide();
show.show();
}
}
else
{
$(this).addClass('checked');
var checkedClasses = buttons.filter('.checked').toArray().map(function(btn){return $(btn).data('filter');}),
selector = '.' + checkedClasses.join('.'),
show = targets.filter(selector);
targets.not(show).hide();
show.show();
}
}
});
});
Now I am implementing the editUser() function. I create function to handle click button
$( "#table-list tbody" ).on( "click", ".btn-edit", function() {
operation = "E";
for (var i in tableStore) {
var temp = JSON.parse(tableStore[i])
if ($(this).attr("data-id") === temp.id) {
$enterID.val(temp.id);
$enterFirstName.val(temp.firstname);
$enterLastName.val(temp.lastname);
$enterLPhone.val(temp.phone);
$enterEmail.val(temp.email);
$enterAddress.val(temp.address);
$enterBirthday.val(temp.birthday);
$enterGender.val(temp.gender);
$enterID.attr("readonly", "readonly");
$enterFirstName.focus();
}
}
});
this help me retrieve data from local storage. Then when I change some information on the input tag I wan to the data will updated into local storage. This is function help me do that:
function editUser(tableStore, user) {
tableStore[tableStore] = user
operation = "A"
}
and when the form is submit I handle it like that:
$( "#table-list tbody" ).on( "click", ".btn-delete", function() {
selected_index = parseInt($(this).attr("data-id").replace("Delete", ""));
$(this).parents('tr').remove()
deleteUserInfor();
});
$(".form-information").on("click", ".btn-save-change", function () {
if (operation == "A"){
var newUser = readUserFromDOM();
addUser(tableStore, newUser.serialize());
localStorage.setItem("tableStore", JSON.stringify(tableStore));
}
else {
var editingUser = readUserFromDOM();
editUser(tableStore, editingUser.serialize());
localStorage.setItem("tableStore", JSON.stringify(tableStore));
}
});
But some thing is wrong and I can't save the data. So can you help me show what is wrong is there.
This my code user manager code pen.
Beside that, the operation is not good idea for the pure function in js. If you can please help me to refactor it
Many thank for your help
Final Update:
https://codepen.io/vikrant24/pen/ybgPww
As shown in below function:
You need to specify tableStore[i] value of i. Because i is the row number. If you are editing row 5th of grid then update tableStore[4]=user likewise if you are updating 3rd row then update tableStore[2]=user. I have added the code for it. I hope you understood.
function editUser(tableStore, user,i) {
tableStore[i] = user
operation = "A"
}
You should use this instead because eventually you would need to update that tableStore in localStorage:
function editUser(tableStore, user,i) {
tableStore[i] = user;
localStorage.setItem("tableStore", JSON.stringify(tableStore));
operation = "A";
}
Previous Answer:
Use this function It will work:
function editUser(tableStore, user) {
tableStore[0] = user
operation = "A"
}
You should use this instead because eventually you would need to update that tableStore in localStorage:
function editUser(tableStore, user) {
tableStore[0] = user;
localStorage.setItem("tableStore", JSON.stringify(tableStore));
operation = "A";
}
I'm having trouble changing the class after making a jquery get request.
code:
<script>
//global variable
var table = []
var numberofaccounts = 0
$(document).ready(function() {
$('#form1').validate();
// add numbers to select ids
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
$('#apply_btn').click(function() {
table = []
var count = 0;
var text = "";
var tracker = 0
$('#stats_table tr').each(function(){
count = 0;
text = "";
$(this).find('td').each(function(){
count++;
if (count == 4) {
text += $( ".select_class"+ tracker + " option:selected" ).val();
} else {
text += " " + $(this).text() + " ";
}
})
table.push(text);
tracker++;
});
$.post("/apply_changes", {"data": JSON.stringify(table)}, function(data) {
var res = JSON.parse(data);
if (res.data == true){
$('#updated').text("Update Successful").css('color', 'green');
$.get("/", function( data ) {
$('#stats_table').load("/ #stats_table");
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
} else {
$('#updated').text("Update Unsuccessful").css('color', 'red');
}
});
});
});
</script>
So when the page first loads this method changes the class on dynamically created select elements.
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
After I make a post to flask the if the response data is true I go ahead and make a get request to grab the updated items from the db. I then refresh the table. This works great if I make one request. However on the second post nothing happens. This is because the classes that I modified at the start of the page load no longer exist. So i added the method above to also trigger after the get response (I also tried at the end of the post response). The problem is that the method doesn't seem to run again. The classes aren't there and as a result when I go to make another post request it can't find the element. How do I go about fixing this?
Things to note: The get request is necessary, the ids and classes cannot be statically assigned.
You are trying to assign classes before you even refresh your table.
$('#stats_table').load("/ #stats_table"); is called asynchronously and returns before it even completes.
You need to put you code, for assigning classes, inside the complete callback of your .load() call:
$('#stats_table').load("/ #stats_table", function() {
numberofaccounts = 0
$(".select_changer").each(function(){
numberofaccounts++;
var new_id = "select_class"+numberofaccounts;
$(this).addClass(new_id);
});
});
I have a function set up with the jQuery cookie plugin: https://github.com/carhartl/jquery-cookie, with the click function on .grid-block it stores each data-hook in an array, saves them as a cookie, then these chosen divs are viewable on the /itin/your-itin/ page. Here's a demo I've set up too: http://nealfletcher.co.uk/itin/ If you click on the .grid-block divs, this will add them to your itinerary, then when you navigate to: http://nealfletcher.co.uk/itin/your-itin/ only these divs are viewable and stored as a cookie for x amount of time. This works great, BUT if I then go back to add more divs, these are stored as a cookie, but the previous ones are wiped, I want to keep appending to the array, store it as a cookie, then when you navigate to: http://nealfletcher.co.uk/itin/your-itin/ it will display all your selections, even if they've been added separately. If that makes sense?
jQuery:
$(window).load(function () {
var cfilter = [];
var $container = $('.block-wrap');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.grid-block',
animationEngine: 'best-available',
filter: '.grid-block',
masonry: {
columnWidth: 151
}
});
$(".grid-block").click(function () {
var thing = $(this).attr("data-hook");
var test = "." + thing;
cfilter.push(test);
$.removeCookie('listfilter', {
path: '/itin/your-itin/'
});
// We need to set the cookie only once
// it stays at the url for 7 days
$.cookie("listfilter", cfilter, {
expires: 365,
path: '/itin/your-itin/'
});
});
if ($.cookie("listfilter") !== 'null') {
// console log just for testing
console.log($.cookie());
$('.block-wrap').isotope({
filter: $.cookie("listfilter")
});
return false;
} else {
// !! this part could be refactored
// as you don't really need to check against the url
// when the cookie doesn't exist show all elements
$('.block-wrap').isotope({
filter: ''
});
}
});
});
Any suggestions would be greatly appreciated!
Change var cfilter = []; to var cfilter = $.cookie("listfilter");
This way you load the changed cookie and add to it instead of overwriting it.
Better code practice would be to check if the cookie exists before using it though, but you get my hint.
You made an error in implementing my change:
if ($.cookie("listfilter") !== 'null') {
var cfilter = [];
} else {
var cfilter = $.cookie("listfilter");
}
is wrong, use
if ($.cookie("listfilter")) {
var cfilter = $.cookie("listfilter");
} else {
var cfilter =[];
}
Can any of you guys help me out with a Javascript problem? I'm trying to write a post expansion feature for my site, and for some reason whenever I expand the first post, the second will no longer expand, and will instead redirect to the full post on the thread page. If I expand the second post and then the first next, I don't have the problem.
Here's the code that runs when the page is loaded:
function postExpansionPrep(){
if(!document.body.className){
var links = document.getElementsByClassName("abbrev");
for (var i = 0; i < links.length; i++ ){
(function(e) {
links[e].firstElementChild.addEventListener("click", function(a){ expandPost(links[e].firstElementChild); a.preventDefault(); }, true);
console.log(links[e].firstElementChild.href);
})(i);
}
}
}
And here's the code that runs when you click on the link to expand a post.
function expandPost(link){
if(link.hash){
$.get(link, function(data) {
var loadedPost = $(data).find("#reply" + link.hash.replace("#",""));
document.getElementById("reply" + link.hash.replace("#","")).lastElementChild.innerHTML = $(loadedPost).find("blockquote").last().html();
});
}
else{
$.get(link, function(data) {
var loadedPost = $(data).find("#parent" + link.pathname.substring(link.pathname.lastIndexOf("/")+1));
document.getElementById("parent" + link.pathname.substring(link.pathname.lastIndexOf("/")+1)).lastElementChild.innerHTML = $(loadedPost).find("blockquote").last().html();
});
}
}
You can see the issue in action here: http://www.glauchan.org/test/
By the way, the feature is opt-in, so you need to enable Post Expansion in the Board Options menu.
The document.getElementsByClassName method returns a live node list. Therefore, the links will change, and potentially have not item at position e any more when the handler is fired - resulting in an undefined value that throws an error when accessing its firstElementChild property.
You should not need to get the current element from the links list. Get it dynamically via a.target or just this:
function postExpansionPrep() {
if (document.body.className)
return;
var links = document.getElementsByClassName("abbrev");
for (var i = 0; i < links.length; i++ ) {
var child = links[i].firstElementChild;
if (!child) // could be null as well
continue;
child.addEventListener("click", function(e) {
expandPost(this);
e.preventDefault();
}, true);
console.log(child.href);
}
}
Btw, as you have jQuery available you should use it, especially for the event handler attaching:
if (!document.body.className)
$(".abbrev > :first-child").click(function(e) {
expandPost(this);
e.preventDefault();
});