Preppend a new child div ahead of previous child div's jquery - javascript

I am trying to a do a simple media posting project. When new records are added to the database I use ajax to add a new child div to a parent div based on the info in the record. I have it working except for the order that children are added in. Doing a prepend does not place the new div as the first child of the parent div, it puts it as the last child of the specified parent. That's no good when I want new posts displayed on top. Here is the code for the file I'm working on. How do I prepend above previously added children?
$(document).ready(function (){
setInterval(function(){
$.ajax({
type: 'GET',
url: 'JSONFile.php',
data: { get_param: 'value' },
dataType: 'json',
success: function(retrieved){
//$("#MainContent").empty();
$.each(retrieved, function(index, i){
$('#MainContent').append('<br><div class="Post"><h2>' + i.UserName + '</h2><br><p>' + i.Content + '</p></div>');
});
}
});
},3000);
});

Instead of using .append, you can use .prepend, which was made for exactly this purpose:
Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
So, you can use the code:
$.each(retrieved, function(index, i){
$('#MainContent').prepend('<br><div class="Post"><h2>' + i.UserName + '</h2><br><p>' + i.Content + '</p></div>');
});

Related

Dynamically-generated table keeps multiplying even though it's being cleared

I have a variety of fields I'm appending to a table (#dvdCollectionBody) in my function loadDvdCollectionView().
The problem: if I click the tag that calls my displayDvd() function, then hit the 'Back' button, everything works as it should. If I click the tag, calling displayDvd() a second time, then click the 'Back' button again, the table will be duplicated, indicating that rows are being appended that aren't getting cleared.
I cannot for the life of me understand why the table keeps appending itself, but only after repeating the process of clicking a 'td' tag more than once.
$(document).ready(function () {
loadDvdCollectionView();
// create on a click
createDvd();
});
function loadDvdCollectionView(){
// hide errors
$('#errorDiv').hide();
// show this view
$('#viewingTable').show();
// empty table body of any preexisting data
$('#dvdCollectionBody').empty();
$.ajax({
type: "GET",
url: "http://localhost:8080/dvds",
success:
function (data, status) { $.each(data, function (index, dvd) {
// append DVD collection to table rows in #dvdCollectionBody
var dvdRow = '<tr><td onclick="displayDvd(' + dvd.dvdId + ')">' + .......
$('#dvdCollectionBody').append(dvdRow);
});
}
// called when <td> tag is clicked
function displayDvd(dvdId){
//hide viewingTable
$('#viewingTable').hide();
// empty preexisting data
$('#releaseYearDisplay, #directorDisplay, #ratingDisplay, #notesDisplay, #dvdTitleHeader').empty();
// show table
$('#dvdDetailsDisplay, #dvdTitleHeader').show();
$.ajax({
type: "GET",
url: "http://localhost:8080/dvd/" + dvdId,
success: function (data) {
$('#dvdTitleHeader').append('
<h3>' + data.title + '</h3>'); $('#releaseYearDisplay').append('
<h3>' + data.releaseYear + '</h3>'); $('#directorDisplay').append('
<h3>' + data.director + '</h3>'); $('#ratingDisplay').append('
<h3>' + data.rating + '</h3>'); $('#notesDisplay').append('
<h3>' + data.notes + '</h3>'); }
}
});
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').hide();
// load main view again
loadDvdCollectionView();
});
}
The problem is that, this piece of code:
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').hide();
// load main view again
loadDvdCollectionView();
});
is placed inside your displayDvd() function.
So when the first time your <td> is clicked, the displayDvd() is called and your #backButton callback is added.
Then you hit the #backButton, the callback function is called, everything should work fine here.
However, when you hit the <td> 2nd time, displayDvd() is called again and another click callback is added to #backButton again, also.
This is where the bug occurred. Now your #backButton have 2 same click callback functions attached. So when you click on it, 2 loadDvdCollectionView() are called simultaneously.
Simply move the piece of code into $(document).ready() callback should fix the problem.
You're hiding the DOM elements, but you're not removing them from the DOM. Try the following to remove the content from dvdDetailsDisplay and dvdTitleHeader:
$('#backButton').click(function(){
// hide current display and header
$('#dvdDetailsDisplay, #dvdTitleHeader').empty();
// load main view again
loadDvdCollectionView();
});

Ajax jQuery Multiple Step Form instead of reloading div, just append new content

I wonder if it's possible to do this multistep form on one single page, so not reloading the div with the content received from the php file but append it right below..
This is what I've got so far:
$(document).on('submit', '#reg-form', function(){
var ln = $('#submit').val();
var id = $('#id').val();
var data = 'submit='+ln;
$.ajax({
type: 'GET',
url : 'step.php',
dataType : 'html',
data : data,
success : function(data)
{
$('#reg-form').fadeOut(500).hide(function()
{
$('.result').fadeIn(500).show(function()
{
$('.result'+id).append(data);
});
});
}
});
return false;
});
Also I tried to use different divs, with incremental id's to put every content in it's own div. The Problem is, I'm only getting the "second" step, so it's not going through the whole formular.
I guess it's because the form of the first page is still there and all have the same id.. Can anyone help me out here please?
id of element in document should be unique. Change the duplicate id at html source or using javascript
success : function(data) {
// change duplicate `reg-form` `id` to value
// corresponding to `.length` of elements having `id`
// containing `"reg-form"`
$(data).filter("#reg-form")
.attr("id", "reg-form-" + $("[id*='reg-form']").length);
$("#reg-form").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result" + id).append(data);
});
});
}

jquery what the best way to reset every positioning to default?

I have a few thumbnails upon clicked, it will display all the works of the user, for example user 1 have 1 work, user 2 have 6 works. By right i will be showing the div accordingly to how many works the user have. If i click on user 1, it show 1 work, i exit and click on user 2, instead of 6 works it show 1 only, because the function takes on what was set on user1, as i didn't reset.. So i wonder if there is a best practices for resetting the show/hide div back to default upon exit, the only solution i know of now is calling the .show each time the function activates, but doesn't seem to be a good way to do things. Please advise
Example
$(function() {
$(".img_thumb_holder").on('click', function() {
var index = $(this).index(); // get current index of clicked thumbnail, so i can call out the related name from captionArray via same index
// what i did to solve the reseting, forcing it to show out each time the function runs
$(".portfolio_thumbImg_holder").show();
$.ajax({
type: "POST",
dataType: "json",
data: ({id: idArray[index]}), // pass the name of clicked holder into php to query
url: "CMS/PHP/retrieveAuthorWorks.php",
success: function(data) {
console.log("Array consist of " + data)
$('.portfolio_thumbImg_holder img').removeAttr("src");
linksArray=[];
titleArray=[];
descArray=[];
$(".full_image_desc .title").html(data[0].title);
$(".full_image_desc .info").html(data[0].desc);
$('.portfolio_thumbImg_holder img').each(function(index, element) {
if (data[index]) {
linksArray.push("http://localhost/testdatabase/cms/" + data[index].links);
$(element).attr("src", linksArray[index]);
titleArray.push(data[index].title);
$(element).attr("title", titleArray[index]);
descArray.push(data[index].desc);
$(element).attr("desc", descArray[index]);
}
});
// check how many divs without the image data, and hide it
$(".portfolio_thumbImg_holder img:not([src])").parent().hide();
}
});
});
});

Are element added by .append() already ready after appended?

I am building a kind of infinite scroll with jquery, but I am facing a DOM ready problem.
var n = 0;
// When user wants to load more, call this
function load_10_images(){
var g; var images = '';
for(g=1; g<=10; g++){
// Create images
images = '<div id="'+n+'" >'+
'<li id="li'+n+'">'+
'<img id="img'+n+'" src="images/loading.gif" />'+
'</li>'+
'</div>';
// add to html
$("#list").append(images);
// change source
$.ajax({
type: "POST",
url: "data.php",
data: {link_n: n},
success: function(resp) {
$("#img"+n).attr("src", resp);
},
});
// ...
n++;
}
}
My problem is images sources don't change. How to solve this problem ?
Your problem is scope. You create the DIVs and IMG ids with n as you loop through it. But you access the value of n in your ajax callback. So it will attempt to find $("#img"+n).attr("src", resp); with whatever the current value of n is (most likely the final value since it will finish faster than the post returns);
The problem is that since AJAX is async, your variable n inside the success call is equal to the variable n inside the last loop. Add a closure like that :
(function(int){
$.ajax({
type: "POST",
url: "data.php",
data: {link_n: int},
success: function(resp) {
$("#img"+int).attr("src", resp);
},
});
})(n);
As many people have pointed out, you have other issues that are causing the problems that you are seeing, but to answer your actual question, yes, they are available after .append(). Actually, what you find people do, frequently, is actually make the element available before appending it. In your code (since you're using jQuery), you could do that like this:
images = $('<div id="'+n+'" >'+
'<li id="li'+n+'">'+
'<img id="img'+n+'" src="images/loading.gif" />'+
'</li>'+
'</div>');
At that point, the element exists and can be read, modified, etc., but simply has not been added to the DOM yet.

How can I append new elments returned by Jquery/AJAX with shapeshift plugin to keep the grid-layout

How can I apply shapeshift to elements returned by AJAX placed in a div and give them the grid layout look ?
Also , it seems that Shapeflit breaks when I use it inside Jquery tabs .. like if I use it inside a tab , when I click on a tab , the grid layout is broken .. How can I fix those two issues ? Otherwise GOOD job with this plugin !!!
For example with AJAX .. when I scroll , new elements are appended with AJAX .. How can I make shapelift be applied to the new appended elements in the loaded_data div
$(window).scroll(function(){
if ($(window).height() + $(window).scrollTop() == $(document).height()) {
// make an ajax call to your server and fetch the next 100, then update
//some vars
var url = '<?php echo $image_url;?>';
$.ajax({
type:'POST',
url: "scroll_data.php",
data:{image_url: '<?php echo $image_url;?>'},
success: function(result){
var obj = $($.parseHTML(result));
// how can I append elements with shapelift so they can keep the grid layout ?
$(".loaded_data").append(obj);
$('.tweet_link').embedly({
key: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
query: {maxwidth:270, maxheight:1100}
});
}
});
}
});

Categories

Resources