I have an ajax script that retrieves more X results from the database. The number of results depend on the offset hidden field value. The script doubles it. After these X new data, it should append after it another block of an image, but I noticed that if I print in the console the selected element, it shows this:
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
[prevObject: m.fn.init[1], context: document, selector: "#revendas_conteudo .load_more .item_estoque:nth-child(6)"]context: documentlength: 0prevObject: m.fn.init[1]selector: "#revendas_conteudo .load_more .item_estoque:nth-child(4)"proto: Object[0]
Which means it's trying to append to something that still doesn't exist. Below is the Ajax script:
function appendAd(offset, no) {
console.log($('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')'));
$('#revendas_conteudo .load_more .item_estoque:nth-child(' + offset + ')').after(
'<div style="float: left; margin-top: 8px; margin-bottom: 8px; width: 100%; text-align: center;" class="anuncio">' +
'<img src="/uploads/publicidades/publicidade_busca_' + no + '.jpg">' +
'</div>'
);
}
$('#revendas_conteudo .btn_carregar_mais').on('click', function (e) {
$.ajax({
url: '/auto/carros/load_more',
data: {
'offset': $('#offset').val(),
'limit': $('#limit').val(),
'no': $('#no').val()
},
success: function (data) {
obj = JSON.parse(data);
i = 0;
max = obj.total === obj.offset;
var newOffset;
no = parseInt($('#no').val()) + 1;
$('#limit').val(obj.limit);
$('#offset').val(obj.offset);
$('#no').val(obj.no);
$.each(obj.res, function (k, v) {
newOffset = parseInt($('#offset').val()) + 1;
$('#revendas_conteudo .load_more').append(
'<div class="item_estoque">' +
'<div class="avatar">' +
'<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
'</div>' +
'<div class="texto_anuncio">' +
'<h4>' + obj.res[i].modelo.substring(0, 19) + '</h4>' +
'<div class="detalhes">' +
'<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
'<span>' + obj.res[i].ano + '</span>' +
'<span>' + obj.res[i].kilometragem + ' km</span>' +
'</div>' +
'<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
'</div>' +
'<div class="texto_anuncio_right">' +
'<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
'Veja Mais' +
'</div>' +
'</div>'
);
i++;
$('#offset').val(newOffset);
$('#no').val(no);
if (newOffset == obj.total) {
$('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
}
});
},
complete: function() {
appendAd($('#offset').val(), no);
}
});
});
How can I do it? To append a block after another HTML block has been appended?
Related
I try to insert a dynamic h3 to a dynamic div, hovewer something is odd as it gets inserted outside the lblUser div. I would also like to be inserted after the "Role" h3.
Here is my code : function showUsers() {
lblUserList.innerHTML = "";
for ( var i = 0; i < ajUserDataFromServer.length; i++ ) {
var lblUser = document.createElement('div');
lblUser.innerHTML = '<div class="lblUser">' + '<img src="' + ajUserDataFromServer[i].image + '" alt="user" class="lblUserImage" data-userImage="' + ajUserDataFromServer[i].image + '">' + '<h3 class="lblUserId">' + 'Id:' + ' ' + ajUserDataFromServer[i].id + '</h3>' + '<h3 class="lblUserRole" data-userRole="' + ajUserDataFromServer[i].role + '">' + 'Role:' + ' ' + ajUserDataFromServer[i].role + '</h3>' + '<h3 class="lblUserName" data-userName="' + ajUserDataFromServer[i].name + '">' + 'Name:' + ' ' + ajUserDataFromServer[i].name + '<h3 class ="lblUserLastName" data-userLastName="' + ajUserDataFromServer[i].lastname + '">' + 'Lastname:' + ' ' + ajUserDataFromServer[i].lastname + '</h3>' + '<h3 class="lblUserPassword" data-userPassword="' + ajUserDataFromServer[i].password + '">' + 'Password:' + ' ' + ajUserDataFromServer[i].password + '</h3>' + '<button id="btnEditUserBody" class="btnShowPage btnEditUser" data-userId="' + ajUserDataFromServer[i].id + '" data-showThisPage="pageUpdateUser">' + 'EDIT USER' + '</button>' + '<button class="btnDeleteUser" data-userId="' + ajUserDataFromServer[i].id + '" >' + 'DELETE USER' + '</button>' + '<h3 class="lblErrorMessage" id="lblDeleteUserErrorMessage">' + '</h3>' + '</div>';
if ( ajUserDataFromServer[i].email ) {
var lblUserEmail = document.createElement('h3');
lblUserEmail.innerHTML = '<h3 class="lblUserEmail" data-userEmail="' + ajUserDataFromServer[i].email + '">' + 'Email:' + ' ' + ajUserDataFromServer[i].email + '</h3>';
lblUser.appendChild( lblUserEmail );
}
if ( ajUserDataFromServer[i].phonenumber ) {
var lblUserPhoneNumber = document.createElement('h3');
lblUserPhoneNumber.innerHTML = '<h3 class="lblUserPhoneNumber" data-userPhoneNumber="' + ajUserDataFromServer[i].phonenumber + '">' + 'Phone-number:' + ' ' + ajUserDataFromServer[i].phonenumber + '</h3>';
lblUser.appendChild( lblUserPhoneNumber );
}
lblUserList.appendChild( lblUser );
}
}
I can see a few things wrong with the code, for example:
var lblUserEmail = document.createElement('h3');
lblUserEmail.innerHTML = '<h3 class="lblUserEmail" data-userEmail="' + ajUserDataFromServer[i].email + '">' + 'Email:' + ' ' + ajUserDataFromServer[i].email + '</h3>';
Should be something like:
var lblUserEmail = document.createElement('h3');
lblUserEmail.classList.add("lblUserEmail");
lblUserEmail.setAttribute("data-userEmail", ajUserDataFromServer[i].email);
lblUserEmail.innerText = 'Email:' + ' ' + ajUserDataFromServer[i].email;
Now you can append it:
lblUser.appendChild(lblUserEmail);
If you do it your way you wil get nested h3 and div elements.
Furthermore, you need to close your img tag. I can advice creating those tags either in code or with the new es5 string interpolation this will clean up your code and will show you these types of errors.
I have a scenario like this:
for (var k in active) {
notifications.append(
'<a href="javascript:toast();">' +
'<div>' +
'<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
'</input>'+
'<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
'<span>' +
'<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
'<br/>' +
'<span class="time">Just Now</span>' +
'</span>' +
'</div>' +
'</input>'+
'</a>');
}
i created dynamic elements using jade template engine.
here i need to identify each <a> click and i nedd to get the value of hidden field.
function toast() {
var grade;
//var phone_number=document.getElementById('phone_number').value;
$.each($('.phone_number'), function () {
grade = $(this).val();
alert(grade);
});
}
by doing this i got a loop of value. which i didn't want. i need single item value. how to solve this ?
pass this to the toast
'<a href="javascript:toast(this);">' +
and change the toast method to
function toast( thisObj )
{
var grade = $( thisObj ).parent().find( '.phone_number[type="hidden"]' ).attr( "value" );
alert( grade );
}
notifications = $(".notifications")
active = [{ phone_number: "982334",expiry_count: "1"},
{ phone_number: "982334",expiry_count: "1"}]
var k;
for (var k in active) {
notifications.append(
'<a href="javascript:toast();">' +
'<div>' +
'<input class="phone_number" type="hidden" id='+active[k].phone_number+' value='+active[k].phone_number+'>'+
'</input>'+
'<span class="notify bg-blue">' + '<i class="fa fa-clock-o"></i>' + '</span>' +
'<span>' +
'<span>Sim ' + active[k].phone_number + ' Expires in ' + active[k].expiry_count + 'days</span>' +
'<br/>' +
'<span class="time">Just Now</span>' +
'</span>' +
'</div>' +
'</input>'+
'</a>');
}
$(document).on('click', 'a', function(){
alert($(this).find('.phone_number').val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notifications"></div>
Its simple.Try this
$(document).on('click', 'a', function(){
alert($(this).find('.phone_number').val())
})
Send the toast function the k you are iterating over
'<a href="javascript:toast(' + k + ');">'
then use k in your function
function toast(k) {
//use k (maybe select by id)
}
I have this json data
somehow i displayed this part of data in html
and want to display this part of data
into div in html but i am unable to display it using for loop and don't to how to start each function from index 1 as index 0 in personal details data.
here is my code
var url = "http://localhost/ReadExchange/api.php";
$.getJSON(url, function(data) {
if (data) {
alert("hey got the data" + JSON.stringify(data));
var arr = data.length;
//$.each(data, function(i,element) {
var element = data[0];
$("#postjson").append(
'<div id="' + element.id + '">' + '<p>' + 'FirstName:' + element.FirstName + '<br/>'
+ 'MiddleName:' + element.MiddleName + '<br/>' + 'LastName:' + element.LastName + '<br/>' + 'Gender:' + element.Gender + '<br/>' + 'Location:' + element.Location + '<br/>' + 'Email:' + element.Email + '<br/>' + 'Mobile:' + element.Mobile + '<br/>' + '</p>' + '</div>'
);
for (var i = 1; i < arr; i++) {
$("#postjson").append(
'<div id="">' + '<p>' + 'BookTitle:' + data[i].data.BookTitle + '<br/>' + 'BookGenre:' + data[i].data.BookGenre + '<br/>' + 'BookWriter:' + data[i].data.BookWriter + '<br/>' + 'Gender:' + data[i].data.BookDescription + '<br/>'
+ '</p>' + '</div>'
);
}
} else {
return;
}
You can use Array.prototype.splice()
data.splice(0, 1);
then iterate data array at for loop, with i set to 0
var data = [{abc:123}, {def:456}];
data.splice(0, 1);
for (var i = 0; i < data.length; i++) {
alert(JSON.stringify(data))
}
I am building a conference website with some concurrent sessions in the schedule.
As you can see in the screenshot the seminar 3 is supposed to be concurrent with seminar 1 & 2 but they are separated. Below kindly find the relevant code. Could anyone tell what the reason might be?
Screenshot of Event Schedule in my Website
_addNewContent = function (msg) {
var lastBlock = false;
var lastConcurrent = false;
if (_page == 1) {
_wrapper.html('');
}
$.each(msg.sessions, function (i) {
if (lastBlock) {
var lastTime = lastBlock.find('.schedule__time').text();
lastTime = lastTime.split('-');
if ($.trim(lastTime[0]) == this.time) {
if (!lastConcurrent) {
lastConcurrent = $('<div class="schedule__concurrent"></div>').appendTo(_wrapper);
}
lastConcurrent.append(lastBlock);
} else {
if (lastConcurrent) {
lastConcurrent.append(lastBlock);
lastConcurrent = false;
} else {
_wrapper.append(lastBlock);
}
}
}
var newBlockString = '<div class="schedule__item ' + _dropdown + ' more-content__item">' +
'<time class="schedule__time" datetime="' + this.time + '">' + this.time + ' - ' + this.end_time + '</time>' +
'<h2 class="schedule__event">' + this.post_title + '</h2>' +
'<div class="schedule__details">';
if (_dropdown) {
newBlockString += ' <a class="schedule__close" href="#"><i class="fa fa-times"></i></a>';
}
newBlockString += '<i class="fa fa-location-arrow"></i> ' + this.location + '' +
'<div class="schedule__layout">' +
'<div class="schedule__speakers-group">'; // schedule__speakers-group
$.each(this.speakers, function () {
var speaker_image = '';
if (typeof (this.post_image[0]) !== 'undefined') {
speaker_image = 'background-image: url(' + this.post_image[0] + ')';
}
var favourite = this.featured ? 'speakers-favorite speakers-favorite_small' : '';
newBlockString += '<a href="' + this.url + '" class="schedule__speaker">' + // schedule__speaker
'<div class="schedule__speaker-pic ' + favourite + '" style="' + speaker_image + '">' +
'<span class="schedule__speaker-hover">' + msg.strings.view_profile + '</span>' +
'</div>' +
'<h3 class="schedule__speaker-name">' + this.post_title + '</h3>' +
'</a>'; // /schedule__speaker
});
newBlockString += '</div>' + // /schedule__speakers-group
'<div class="schedule__info">' +
'<div class="schedule__text">' + this.post_excerpt + '</div>' +
'<div class="schedule__labels">';
$.each(this.tracks, function () {
newBlockString += '<span class="label" style="background-color:' + this.color + ';">' +
this.name +
'</span> ';
});
newBlockString += '</div>' +
'' + msg.strings.more_info + '' +
'</div>' + // /schedule__info
'</div>' + // /schedule__layout
'</div>' + // /schedule__details
'</div>'; // /schedule__item
var newBlock = $(newBlockString);
if (msg.sessions.length == 1 || msg.sessions.length == i + 1) {
_wrapper.append(newBlock);
}
lastBlock = newBlock;
});
var newItems = _wrapper.find('.hidden');
setTimeout(function () {
$.each($('.schedule__items'), function () {
new ScheduleOpen($(this));
});
}, 10);
setTimeout(function () {
_heightAnimation(msg.has_items, newItems);
}, 50);
},
I guess your website first read an array of conference sessions before running this whole function.
And I found this part
if (msg.sessions.length == 1 || msg.sessions.length == i + 1) {
_wrapper.append(newBlock);
}
may prevents some of the conference sessions becoming concurrent to the last conference session, especially the last array item.
You can change it to
if (msg.sessions.length == 1) {
_wrapper.append(newBlock);
}
if (msg.sessions.length == i + 1) {
if (lastConcurrent) {
lastConcurrent.append(newBlock);
} else {
_wrapper.append(newBlock);
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have the following function from where i want to return the htm value however i am getting an undefined. I get a return value as i have checked that already.
function loadData(uid) {
$.ajax({
type: "POST",
url: '<%= page.resolveURL("~")%>Haggler.asmx/getLovedProductsSellerStoreByFbId',
//url: '<%= Page.ResolveUrl("~")%>Haggler.asmx/GetFacebookFriends',
data: '{FacebookId:' + uid + ',pageIndex:' + JSON.stringify(pageIndex) + '}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: true,
// Page parameter to make sure we load new data
success: function (data) {
var myObject = eval('(' + data.d + ')');
//alert('getProductDescription' + JSON.stringify(myObject));
var html = '';
pageIndex++;
var htmlCategoryList = '';
var i = 0, length = myObject.length;
var _productLink = '';
var _productFullLink = '';
if (length > 0) {
pageCount = myObject[0].PageCount;
if (length > 0) {
for (; i < length; i++) {
if (myObject[i].ShippingQuantity > 0) {
_productLink = myObject[i].SellReqID + '/product/' + myObject[i].CurrentNodeName;
_productFullLink = "http://www.xarato.com/" + myObject[i].SellReqID + "/product/" + myObject[i].CurrentNodeName;
if (myObject[i].Discount == 0) {
/**
if (parts[parts.length-1] == 'loves') {
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><a href="/' + _productLink + '"><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].
html += '<li class="polaroid"><div style="position:relative;"><img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '"_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '"><div class="options"><span class="favs" id="span' + myObject[i].SellReqID + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].SellReqID + ')">like it!</span></div></div><div class="prod"><span>' + myObject[i].RequestTitle + '</span></div><div class="prodprice1"><span style="font-weight:700;">Rs. ' + Math.round(parseFloat(myObject[i].MRPrice) + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{ **/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
else {
/**if (parts[parts.length-1] == 'loves') {
var _finalPrice = parseFloat(myObject[i].MRPrice) - (parseFloat(myObject[i].Discount) * parseFloat(myObject[i].MRPrice))/100
html += '<li class="polaroid"><div class="prodoptionbg prodseller"><span>Listed by ' + myObject[i].FirstName + ' ' + myObject[i].LastName + '</span></div><div style="position:relative;"><img alt="' + myObject[i].NodeName + '" src="/' + myObject[i].Preview + '_thumb.jpg" width="200" height="' + myObject[i].Height + '"><div class="options"><span class="favs" id="span' + myObject[i].NodeId + '">' + myObject[i].Likes + '</span><span class="fav" onclick="calculateLike(event,' + myObject[i].NodeId + ')">like it!</span></div><div class="kjss"><span>' + myObject[i].Discount + '% Off</span></div></div><div class="prod"><span>' + myObject[i].NodeName + '</span></div><div class="prodprice1"><span style="color:#777777; text-decoration:line-through">Rs. ' + myObject[i].MRPrice + '</span> <span style="font-weight:700;">Rs. ' + Math.round(_finalPrice + parseFloat(myObject[i].ShippingPrice)) + '</span></div></li>';
}else{**/
//alt="' + myObject[i].RequestTitle + '"
html += '<img alt="' + myObject[i].RequestTitle + '" src="/' + myObject[i].Image1 + '_thumb.jpg" width="200" height="' + myObject[i].ThumbHeight1 + '">';
//}
}
}
}
if (clearHtml) {
// $('.bxslider').html('');
//htm = '<li>"' + html + '"</li>';
}
// var htmli = '<li>"' + html + '"</li>';
// $('.bxslider').append(htmli);
htm = '<li>' + html + '</li>';
alert(htm);
return htm;
clearHtml = false;
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#main'), // Optional, used for some extra CSS styling
offset: 17, // Optional, the distance between grid items
itemWidth: 225 // Optional, the width of a grid item
};
}
else {
return;
}
}
else {
return;
}
},
failure: function (data) {
alert('failture');
},
error: function (data) {
alert(data.responseText);
}
});
}
This is how i am taking the data but i get an undefined value.
HtmlM += loadData(myObject.data[i].uid);
Please help me out.
Change your loadData to
function loadData(uid, delegate) {
///In ajax instead of return use
delegate(htm);
}
then call like that
loadData(myObject.data[i].uid, function(html){ HtmlM += html ;});
Ajax is asynchronous so you cant just return (yes you can do it synchronous but its not right way)