I have an activity stream for both users use, and site-wide view. Currently when a user posts an update, I have it displaying a default bootstrap success alert. I have seen other websites append the new post to the list by sliding down the existing items, and appending the newest post to the top of the list.
I am attempting to do just that, but I am not sure how to add it with all the proper styling. (code below). I am tried adding all the <div> tags that make up one activity item in my feed, but without success.
TL;DR - Is there a way to have ajax look at the current top activity item, clone it, and append it to the top? It would make the code more dynamic for my use, and avoid having to place CSS inside the .js file.
jQuery(document).ready(function ($) {
$('form#postActivity').submit(function (event) {
event.preventDefault();
$postActivityNow = (this);
var subject = $('#activity_subject').val();
var message = $('#activity_content').val();
var data = {
'action': 'postAnActivity',
'subject': subject,
'message': message,
}
$.ajax({
type: 'post',
url: postAnActivityAjax.ajaxurl,
data: data,
error: function (response, status) {
alert(response);
},
success: function (response) {
if (response.success) {
bootstrap_alert.success('Activity Added');
} else {
if (response.data.loggedIn == false) {
bootstrap_alert.warning('you are NOT logged in');
console.log('you are not logged in')
}
if (response.data.userExists == false) {
console.log(response);
bootstrap_alert.warning(response.data.alertMsg);
console.log(response.data.alertMsg)
}
}
}
});
});
});
you can also use .prependTo()
var newActivity = $( ".activity" ).first().clone();
newActivity.prependTo( ".parentDiv").hide().slideDown();
FIDDLE
To clone an element: jQuery.clone()
var newItem = $("#myDiv").clone();
To append it as first child: jQuery.prepend()
$("#parentDiv").prepend( newItem );
Regards,
hotzu
I have already done in the past using $.prepend()
Check this url for more information jquery append to front/top of list
Related
I have a chat application that works similar to hangouts. When you click on a user the chat div is generated. A simple feature I have is to allow them to press enter in a textarea to send the text, which works fine but if I have multiple dynamically generated jQuery functions only the LAST function will still work. I assume its stopping the previous instances from running. How do I fix this?
Again when the user starts a chat it loads the scripts for that chat session because I assume I need a unique ID rather than a class name so I could pass the ID to the database - probably not the most efficient way to do things I know:
echo "$('#im-textbox".$receiver_id."').on('keyup', function(event){
if (event.keyCode == 13) {
//$(this.form).submit()
var dataset = $('#im-form".$receiver_id."').serialize();
$.ajax({
url: 'data/add-chat.php',
data: dataset,
method: 'post',
success: function(data) {
console.log(data);
}
});
$('#im-textbox".$receiver_id."').val('')
return false;
}
});
";
Thank you for your help!
I fixed it with this...
$(document).on('keyup', '#im-textbox".$receiver_id."', function(event){
if (event.keyCode == 13) {
//$(this.form).submit()
var dataset = $('#im-form".$receiver_id."').serialize();
$.ajax({
url: 'https://easyrepair.us/manage/data/add-chat.php',
data: dataset,
method: 'post',
success: function(data) {
console.log(data);
}
});
$('#im-textbox".$receiver_id."').val('')
return false;
}
});
I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});
I have two separate AJAX calls. One that gets a list of items from a txt file and creates an HTML table out of them and one that talks to a database to find how much each item costs and then lists this in the corresponding table cell for each item (I know this may sound like a strange approach, but it's a good option in our case...).
The issue is that the price is not getting written to the table since the table is created (or to be precise, the rows of the table are created) after the page loads. I'm not sure how to fix this.
$(document).ready(function() {
makeItemTable();
listPrices();
...
});
function makeItemTable() {
$.ajax({
url: 'products.php',
type: 'GET'
})
.done(function(response) {
$('.price-table > tbody').html(response);
})
}
function listPrices() {
.ajax({
url: 'prices.php',
type: 'GET'
})
.done(function(response) {
priceData = $.parseJSON(response);
$('.price-table tr').each(function() {
var item = $(this).find('td:nth-child(1)').text();
if (priceData[item]) {
var price = priceData[item];
$(this).find('td:nth-child(2)').text(price);
}
})
}
You can try
Using setTimeout to check request to 'products.php' execute callback done (inside callback for request to 'prices.php')
Another way
var jqxhr1 = $.ajax("products.php");
var jqxhr2 = $.ajax("prices.php");
$.when(jqxhr1, jqxhr2).done(function(jqxhr1, jqxhr2) {
// Handle both XHR objects
alert("all complete");
});
Call function listPrices() inside callback request to 'products.php'
Hope to help
I am trying to do an ajax pagination with the following code:
// AJAX pagination
$(".pages .prev").live('click', function(event) {
event.preventDefault()
var current_page = parseInt(getParameterByName('page'))-1;
$.get('/ajax/financial_page/', {'page': current_page}, function(response) {
$(".content table").replaceWith(response)
});
})
And in my view function:
def financial_page(request):
"""
Returns a single financials page, without extra HTML (used in AJAX calls).
"""
page = int(request.GET.get('page', 1))
if request.user.is_superuser:
fs = FinancialStatements.objects.order_by('-date', 'statement_id')
else:
up = request.user.get_profile()
providers = up.provider.all()
fs = FinancialStatements.objects.filter(provider__in=providers).order_by('-date', 'statement_id')
fs_objects, current_page_object, page_range = paginator(request, objects=fs, page=page, number_per_page=30)
data = { 'fs':fs_objects,
'page_range': page_range,
'current_page': current_page_object,
}
page = render_to_string('financial_section.html', data, RequestContext(request))
return HttpResponse(simplejson.dumps([page]))
However, there are two problems I'm running into. The first is that the response is not really HTML, and has a bunch of n\t\t\n\t\t\n\t\n\t\n\t\n\t\t\n\t\, etc. Also, I'm having trouble keeping track of the current page/changing the url as needed. How would I build a functional ajax pagination here?
Update: I figured out the first one, by doing response = $.parseJSON(response);. How would I keep track of which page I am on though?
To keep track of the page, you can increment/decrement a variable on click with your AJAX function. Try this:
var counter="0";
$(document.body).on('click', ".pages .prev, .pages .next", function(event) {
if($(this).hasClass('prev')
counter--;// <--decrement for clicking previous button
else if($(this).hasClass('next')
counter++; // <--increment for clicking next button
event.preventDefault()
$.get('/ajax/financial_page/', {'page': counter}, function(response) {
$(".content table").replaceWith(response)
});
})
I would also not use live method as it is deprecated as of jQuery 1.7. It has been replace by the on method. See the jQuery on() API here: http://api.jquery.com/on/
Check this tutorial about "Ajax Scroll Paging Using jQuery, PHP and MySQL", it may simplify your job:
http://www.bewebdeveloper.com/tutorial-about-ajax-scroll-paging-using-jquery-php-and-mysql
Here is the essential from:
var is_loading = false; // initialize is_loading by false to accept new loading
var limit = 4; // limit items per page
$(function() {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (is_loading == false) { // stop loading many times for the same page
// set is_loading to true to refuse new loading
is_loading = true;
// display the waiting loader
$('#loader').show();
// execute an ajax query to load more statments
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {last_id:last_id, limit:limit},
success:function(data){
// now we have the response, so hide the loader
$('#loader').hide();
// append: add the new statments to the existing data
$('#items').append(data);
// set is_loading to false to accept new loading
is_loading = false;
}
});
}
}
});
});
Try using the javascript String.replace() method:
// AJAX pagination
$(".pages .prev").live('click', function(event) {
event.preventDefault()
var current_page = parseInt(getParameterByName('page'))-1;
$.post('/ajax/financial_page/', {'page': current_page}, function(response) {
response = response.replace(/\n/g,'<br>').replace(/\t/,' ');
$(".content table").replaceWith(response)
});
})
jQuery.get(url, [data], [callback], [type])
type :xml, html, script, json, text, _default。
how about trying to define the last parameter as "html" ?
I have a simple jQuery function that resizes text areas, and I want it to apply to all text areas.
For the most part, this works great:
$(document.ready(function(){$("text_area").resizer('250px')});
However, because it is only called once when the document is ready, it fails to catch text areas that are later added onto the page using Ajax. I looked at the .live() function, which seems very close to what I'm looking. However, .live() must be bound to a specific event, whereas I just need this to fire once when they're done loading (the onLoad event doesn't work for individual elements).
The only thing I can get working is a really obtrusive inclusion of the JavaScript call directly into the Ajax. Is that the recommended way to be doing this?
Edit: Here is the rails source code for what it does for Ajax requests:
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
var link = $(this);
if (!allowAction(link)) return false;
if (link.attr('data-remote') != undefined) {
handleRemote(link);
return false;
} else if (link.attr('data-method')) {
handleMethod(link);
return false;
}
});
// Submits "remote" forms and links with ajax
function handleRemote(element) {
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else {
method = element.attr('data-method');
url = element.attr('href');
data = null;
}
$.ajax({
url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
});
}
So in my particular case, I've got a link, that has data-remote set to true, which points to a location that will return JavaScript instructing a form containing a text area to be appended to my document.
A simple way to do this would be to use ajaxComplete, which is fired after every AJAX request:
$(document).ajaxComplete(function() {
$('textarea:not(.processed)').resizer('250px');
});
That says "every time an AJAX request completes, find all textarea elements that don't have the processed class (which seems to be added by the resizer plugin -- terrible name for its purpose!) and call the resizer plugin on them.
You may be able to optimise this further if we could see your AJAX call.
Generally speaking, I would do it this way..
$.ajax({
type : "GET",
url : "/loadstuff",
success: function(responseHtml) {
var div = $("#containerDiv").append(responseHtml);
$("textarea", div).resizer("250px");
}
});
Wondering if you could use .load for this. For example:
$('text_area').load(function() {
$("text_area").resizer('250px');
});