Bootstrap popover and loading content with ajax and django - ajax

I know it has been given some answers but I will go for it :). As the title says i want to add popover bootstrap but with ajax loaded content. my html, but i want a Loading message to appear first and then the content.
<p class='entry' data-adjaxload = '/calendar/entry/1'>Title1</p>
<p class='entry' data-adjaxload = '/calendar/entry/2'>Title2</p>
<p class='entry' data-adjaxload = '/calendar/entry/3'>Title3</p>
my django view is the following
def entry_details(request, entry_id):
entry = get_object_or_404(Entry, pk=entry_id)
args = dict(entry=entry, user=request.user)
if request.is_ajax():
return render_to_response('mycal/ajax/entry_details.html', args)
else:
entry_form = EntryForm(instance=entry)
args.update(entry_form=entry_form)
return render_to_response('mycal/entry_details.html', args)
Pretty simple. I am using the same view to either load html content via ajax in the popover, or a details page via normal get request
the ajax details page:
<div class="entry">
<p>{{entry.title}}</p>
<p>{{entry.date}}</p>
<p>{{entry.customer}}</p>
</div>
and the script
$(document).ready(function(){
$('p.entry').each(function (){
var i = $(this);
$(i).bind('mouseenter', function(){
i.popover({
html:True,
title:i.html(),
content:'Loading'
}).popover('show');
$.ajax({
url:i.data('ajaxload'),
dataType:'html',
success:function (data){
i.popover({content:data}).popover('show');
}
});
});
$(i).bind('mouseleave', function(){
i.popover('hide');
});
});
});
But whilst it does run tha ajx and fetches the html, it won't load them onto the popover. How can I change that?

Just fiddled what you are looking for with popover content being updated dynamically using echo/json.
Just roll over the p element and wait for the 3 second delay.
If as you say, the data is being loaded properly then the only change needed is:
var popover = i.data('popover');
popover.options.content = data.text;
i.popover('show');

Related

AJAX call with nodeJS and express successful, but not displaying data

I have recently migrated from a codeigniter framework, to a nodejs with an express framework. Our codeigniter site had a lot of JS as it was, and we made a lot of AJAX calls because it is a single page app. We are messing around with node and express now, and I cannot get a simple AJAX call to function. It could be a lack of understanding of node, it could be something else. We are using openshift to host. We are using hogan-express as a template.
server.js
var express = require('express');
var fs = require('fs');
var http = require('http');
var path = require('path');
var SampleApp = function() {
var self = this;
self.initializeServer = function() {
self.app = module.exports = express();
self.app.configure(function() {
self.app.set('views', __dirname + '/views');
self.app.set('view engine', 'html');
self.app.engine('html', require('hogan-express'));
//self.app.set('layout', 'layout') # use layout.html as the default layout
self.app.use(express.favicon());
self.app.use(express.logger('dev'));
self.app.use(express.bodyParser());
self.app.use(express.methodOverride());
self.app.use(express.session());
self.app.use(self.app.router);
self.app.use(require('stylus').middleware(__dirname + '/public'));
self.app.use(express.static(path.join(__dirname, 'public')));
});
require('./routes');
}
There is more code in this file, I am only including the relevant code (I think).
Ajax.html
<div id="button">
<button id="testbutton">Push Me!</button>
</div>
<div id="populate">{{title}}</div>
<div id="null">{{>part}}</div>
<script type='text/javascript'>
$(function(){
$('#testbutton').click(function (){
$.ajax({
url:'/test',
type: 'POST',
success: function(result){
alert('success!');
},
error: function(){
alert("well this is embarassing... if the problem persists please let us know at facebook.com/stembuds");
}
});
});
});
</script>
index.js
app = require('../server');
app.get('/', function(req, res){
res.render('ajax');
});
app.post('/test', function(req, res){
console.log('get');
res.locals = {title: 'Horray'};
res.render('ajax', {partials:{part:'part'}});
});
part.html
<p> pass me in!!</p>
So basically what I am trying to do is when the button is clicked I want the ajax call to show a partial view. The way we are going to structure the site is to have one single page, and have the ajax calls render different views based on the buttons that the user clicks. So here is the interesting part: I get the success alert from the ajax call, but the {{title}} and the {{>part}} never show up. However, when I go to the console and click 'network', and then click 'test' (the url to my ajax call), the response shows the divs populated with "Horray" and "pass me in!!". Sorry for the length, and thank you for any information you can provide us.
If you are calling your resources with ajax (as you are doing) then you get the response to your ajax function. After successful call you need to render the view in your client side JS code.
What I mean is that your code works as expected, but your backend cannot update your browsers view. You need to do it client side or load the whole page again from the server.
Your success hander could be something like this:
success: function(result){
renderTheResults(result);
},
You can just send the JSON. You need to send the json via send not render. Because render is supposed to deliver the full HTML page. May be .ejs file.
For example:
res.send({partials:{part:'part'}});
res.send should be used to pass json to your page. And on your page you have to use the JSON to populate the HTML dynamically.

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();
});

jQuery: Get next page via ajax and append it with animation

I am getting next page on my wordpress blog using jquery, finding the desired div and appending it to the existing one. This part works without a problem. But, what I need to do is, to add slideDown animation to it.
This is how my working code so far looks like:
$.get(next_page, function(data) {
var response = $(data);
var more_div = $(response).find('.FeaturedRow1').html();
$('.FeaturedRow1').append(more_div).slideDown('slow');
$('.navigation').not(':last').hide();
I tried adding hide() to response, more_div as well as append lines. In the first case, I get error stating that it cannot set property display of undefined.
In the second case, in the console it display HTML and says "has no method hide". I also tried adding a line $(more_div).hide() but again, I get the error "Uncaught TypeError: Cannot set property 'display' of undefined".
If I use hide in the 3rd line
$('.FeaturedRow1').hide().append(more_div).slideDown('slow');
it hides the whole FeaturedRow1 div and animates it, that takes me to the top of the div, which is what I don't want.
EDIT: Here's the important HTML structure and jQuery code for the desired section
<div class="FeaturedRow1">
<div class="postspage">
//list of posts here
</div>
<div class="navigation">
<span class="loadless">
//hyperlink to previous page
</span>
<span class="loadmore">
//hyperlink to next page
</span>
</div>
</div>
When you click on the hyperlink inside the loadmore, the following jQuery code gets called
$('.loadmore a').live('click', function(e) {
e.preventDefault();
var next_page = $(this).attr('href');
$.get(next_page, function(data) {
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow')
$('.navigation').not(':last').hide();
});
});
$('.loadless').live('click', function(e) {
e.preventDefault();
if ($('.postpage').length != 1) {
$('.postpage').last().remove();
}
$('.navigation').last().remove();
$('.navigation').last().show();
});
You get error as you are using html method which returns a string not a jQuery object, try the following.
var $response = $(data);
var $more_div = $response.find('.FeaturedRow1').hide();
$more_div.appendTo('.FeaturedRow1').delay(100).slideDown('slow');
//$('.navigation').not(':last').hide();
Update:
$.get(next_page, function(data) {
var $response = $(data);
var more_div = $response.find('.FeaturedRow1').html();
$('<div/>').hide()
.append(more_div)
.appendTo('.FeaturedRow1')
.delay(100)
.slideDown('slow')
$('.navigation').not(':last').hide();
});

How to load plain text in to div from another page

I'm trying to load content from another page div into another page div.
What i've got:
JQUERY:
$('#news_date-1').load('test.php .news_date-1');
TEST.PHP
<div class="news_date-1">20-11-2009</div>
Destination.html
<div id="news_date-1"></div>
The result i get =
<div id="news_date-1"><div class="news_date-1">20-11-2009</div></div>
The result i want =
<div id="news_date-1">20-11-2009</div>
Can anybody help out?
You can try calling unwrap() on it in the callback.
$('#news_date-1').load('test.php .news_date-1', function () {
$(this) //will refer to #news_date-1
.find('.news_date-1') //find the inserted div inside
.contents() //find all its contents
.unwrap(); //unwrap the contents, thus removing the unneeded div
});
This is not the most beautiful solution, because .load() already inserts it into the DOM, and then you tamper with the DOM again, which should be minimized.
Another way I see is using $.get() instead:
$.get('test.php', function(receivedHtml) {
//getting only the parts we need
var neededHtml = $(receivedHtml).find('.news_date-1').html();
//adding it to DOM
$('#news_date-1').append(neededHtml);
});
Try this:
$.get('test.php', function(data) {
$('#news_date-1').append($(data).find('.news_date-1'));
});

Update using Prototype and Ajax

I am using Ajax and Prototype. In my code, I need to update the contents of a div.
My div:
<div id="update">
1. Content_1
</div>
My code:
Element.update($("update"),"2.Content_2");
Expected output:
<div id="update">
1.Content_1
2.Content_2
</div>
How can I do this in Ajax and Prototype?
AJAX usually means you are executing a script on the server to get this result.
However, in your example it looks like you simply want to append some text.
To append text you could simply add the text to the end of the innerHTML:
$("update").innerHTML = $("update").innerHTML + "2.Content_2";
If you are wanting to execute a server script, I'd do this: (I haven't used Prototype for a while, things might have changed)
function getResult()
{
var url = 'theServerScriptURL.php';
var pars = '';
var myAjax = new Ajax.Request(
url,
{
method: 'post',
parameters: {},
onComplete: showResult
});
}
function showResult(originalRequest)
{
$("update").innerHTML = originalRequest.responseText;
}
This code will call 'theServerScriptURL.php' and display the result in the div with id of 'update'.

Resources