How to only append once when loading in html Ajax - ajax

I loading in content from a JSON file in a lightbox I have created. The light box opens up another html. In that html I append data loaded in from the JSON file to various elements. However I only want to append once when they open the lightbox, how can I do this?
$(document).on('click', '.mch-overlay-info', function(e){
e.preventDefault();
var href = $(this).attr('href');
$('#mch-overlay-content').html('');
$('#mch-overlay').fadeIn(300);
$('#mch-overlay-content').load(href, function() {
showInfo();
});
});
function showInfo(){
$(".start .text3").append(data[lang]['startpage']['text3']);
$(".start .text4").append(data[lang]['startpage']['text4']);
$(".start .text5").append(data[lang]['startpage']['text5']);
}

I'm assuming your problem is that every time they click it appends? Two options:
Don't append it. just use $().html() to set the content and replace the old content.
Control with a variable
var hasBeenAppended = false;
//etc...
function showInfo(){
if(!hasBeenAppended) {
hasBeenAppended = true;
$(".start .text3").append(data[lang]['startpage']['text3']);
$(".start .text4").append(data[lang]['startpage']['text4']);
$(".start .text5").append(data[lang]['startpage']['text5']);
}
}

Related

How to Increase dropzone for kenoui upload widget

The only type of documentation I can find referencing to "drop zone" is
localization.dropFilesHere String(default: "drop files here to upload")
Sets the drop zone hint.
Now how can I set the dropzone to the whole page like Blueimp?
Why not just override the default dropzone size? You can increase the size using basic css.
var $dropzone = $("div.k-dropzone");
$dropzone.css("height", "mycustomHeight");
$dropzone.css("width", "mycustomWidth");
Good luck.
This should delegate the drop event from "largedroparea" to kendo upload
<div id="largedroparea"></div>
<input type="file" name="files" id="photos" />
<script>
$("#photos").kendoUpload({
async: {
saveUrl: "save",
removeUrl: "remove"
}
});
// Setup the dnd
$('#largedroparea').on('dragenter', handleDragEnter);
$('#largedroparea').on('dragover', handleDragOver);
$('#largedroparea').on('dragleave', handleDragLeave);
$('#largedroparea').on('drop', handleDrop);
function handleDragEnter(e) {
}
function handleDragOver(e) {
e.stopPropagation();
e.preventDefault();
// Explicitly show this is a copy.
e.originalEvent.dataTransfer.dropEffect = 'copy';
}
function handleDragLeave(e) {
}
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
var event = jQuery.Event("drop");
event.originalEvent = e.originalEvent;
$('#photos em').trigger(event);
}
</script>
With the current version of Kendo UI Uploader it's not possible to increase the dropzone size.
Possible alternatives :
Create a div surrounding your page , whenever the files are dropped in this div create a List like filesToUpload of the dropped files and then assign this list to the files option of kendo upload.
files: filesToUpload,
Steps to grab the dropped files:
Stop the default behaviour in the drop event of your dropzone div
$("#yourDropzoneDiv").on("dragover", function (event) {
event.preventDefault();
event.stopPropagation();
});
$("#yourDropzoneDiv").on("dragleave", function (event) {
event.preventDefault();
event.stopPropagation();
});
$("#yourDropzoneDiv").on("drop", function (e) {
e.preventDefault();
e.stopPropagation();
var filesToUpload = [];
for (var i = 0; i < e.originalEvent.dataTransfer.files.length; i++) {
var objDroppedFiles = {};
objDroppedFiles['name'] = e.originalEvent.dataTransfer.files[i].name
objDroppedFiles['size'] = e.originalEvent.dataTransfer.files[i].size
objDroppedFiles['extension'] = e.originalEvent.dataTransfer.files[i].type.split('/')[1]
filesToUpload.push(objDroppedFiles);
}
$("#droppedUploader").kendoUpload({
multiple: true,
async: {
saveUrl: "Upload.aspx",
autoUpload: true
},
files: filesToUpload,
upload: fileUploadDropped,
template: kendo.template($('#droppedFileTemplate').html())
});
}
This way you will be able to see the dropped files in your kendo uploader.
Have you tried using CSS to accomplish that? Simply:
div.k-dropzone {
height:150px;
}
This will make your dropzone bigger. Please do not that it pushes the file list downward.
Hope it helps.

hash in url to deep linking with ajax

I've this code to load content in a div #target with some animation. Works fine but i don't know how implement code to change link and url with #hash!
How can I do this?
the code:
$(document).ready(function(){
$("#target").addClass('hide');
$('.ajaxtrigger').click(function() {
var pagina = $(this).attr('href');
if ($('#target').is(':visible')) {
}
$("#target").removeClass('animated show page fadeInRightBig').load(pagina,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
return false;
});
});
Try to use any javascript router. For example, router.js.
Modify you code like this(I didn't check if this code work, but I think idea should be clear):
$(document).ready(function(){
var router = new Router();
//Define route for your link
router.route('/loadpath/:href', function(href) {
console.log(href);
if ($('#target').is(':visible')) {
$("#target").removeClass('animated show page fadeInRightBig').load(href,
function() {
$("#target").delay(10).transition({ opacity: 1 })
.addClass('animated show page fadeInRightBig');
}
);
}
});
router.route('', function(){ console.log("default route")});
$("#target").addClass('hide');
// Instead of loading content in click handler,
// we just go to the url from href attribute with our custom prefix ('/loadpath/').
// Router will do rest of job for us. It will trigger an event when url hash is
// changes and will call our handler, that will load contents
// from appropriate url.
$('.ajaxtrigger').click(function() {
router.navigate('/loadpath/' + $(this).attr('href'));
return false;
});
});

Loading images with ajax (in rails) [duplicate]

I want to load external images on my page asynchronously using jQuery and I have tried the following:
$.ajax({
url: "http://somedomain.com/image.jpg",
timeout:5000,
success: function() {
},
error: function(r,x) {
}
});
But it always returns error, is it even possible to load image like this?
I tried to use .load method and it works but I have no idea how I can set timeout if the image is not available (404). How can I do this?
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
IF YOU REALLY NEED TO USE AJAX...
I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:
Solution 1
Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.
$.ajax({
url : 'BASE64_IMAGE_REST_URL',
processData : false,
}).always(function(b64data){
$("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});
Solution2:
Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:
var url = 'IMAGE_URL';
$.ajax({
url : url,
cache: true,
processData : false,
}).always(function(){
$("#IMAGE_ID").attr("src", url).fadeIn();
});
However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.
cheers,
will
Using jQuery you may simply change the "src" attribute to "data-src". The image won't be loaded. But the location is stored with the tag. Which I like.
<img class="loadlater" data-src="path/to/image.ext"/>
A Simple piece of jQuery copies data-src to src, which will start loading the image when you need it. In my case when the page has finished loading.
$(document).ready(function(){
$(".loadlater").each(function(index, element){
$(element).attr("src", $(element).attr("data-src"));
});
});
I bet the jQuery code could be abbreviated, but it is understandable this way.
$(<img />).attr('src','http://somedomain.com/image.jpg');
Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.
You can use a Deferred objects for ASYNC loading.
function load_img_async(source) {
return $.Deferred (function (task) {
var image = new Image();
image.onload = function () {task.resolve(image);}
image.onerror = function () {task.reject();}
image.src=source;
}).promise();
}
$.when(load_img_async(IMAGE_URL)).done(function (image) {
$(#id).empty().append(image);
});
Please pay attention: image.onload must be before image.src to prevent problems with cache.
If you just want to set the source of the image you can use this.
$("img").attr('src','http://somedomain.com/image.jpg');
This works too ..
var image = new Image();
image.src = 'image url';
image.onload = function(e){
// functionalities on load
}
$("#img-container").append(image);
AFAIK you would have to do a .load() function here as apposed to the .ajax(), but you could use jQuery setTimeout to keep it live (ish)
<script>
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
$("#placeholder").load("PATH TO IMAGE");
var refreshId = setInterval(function() {
$("#placeholder").load("PATH TO IMAGE");
}, 500);
});
</script>
use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:
$("#img_id").error(function(){
//$(this).hide();
//alert("img not loaded");
//some action you whant here
});
careful - .error() event will not trigger when the src attribute is empty for an image.
//Puedes optar por esta soluciĆ³n:
var img = document.createElement('img');
img.setAttribute('src', element.source)
img.addEventListener('load', function(){
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#imagenesHub").append(img);
}
});
$(function () {
if ($('#hdnFromGLMS')[0].value == 'MB9262') {
$('.clr').append('<img src="~/Images/CDAB_london.jpg">');
}
else
{
$('.clr').css("display", "none");
$('#imgIreland').css("display", "block");
$('.clrIrland').append('<img src="~/Images/Ireland-v1.jpg">');
}
});

"Load More Posts" with Ajax in wordpress

I am trying to create ajax pagination on Blog Page..
What I need to do is to display 5 posts initially and then load 5 more when "load more posts" link is clicked.
Below is the javascript I am using:
<script>
jQuery(document).ready(function() {
// ajax pagination
jQuery('.nextPage a').live('click', function() {
// if not using wp_pagination, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('.blogPostsWrapper').html('<div><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('.blogPostsWrapper').load(link+' .post')
});
}); // end ready function
</script>
The problem is that when I click the link the old posts get replaced by the new ones, I need to show old posts as well as the new posts...
Here is the Updated jQuery Code which enables the ajax pagination.
jQuery(document).ready(function(){
jQuery('.nextPage a').live('click', function(e){
e.preventDefault();
var link = jQuery(this).attr('href');
jQuery('.blogPostsWrapper').html('Loading...');
jQuery('.blogPostsWrapper').load(link+' .post');
});
});
The only problem now is the old posts get removed, i need to keep both old and new posts..
Here is the final code I used and now everything works perfectly...
// Ajax Pagination
jQuery(document).ready(function($){
$('.nextPage a').live('click', function(e) {
e.preventDefault();
$('.blogPostsWrapper').append("<div class=\"loader\"> </div>");
var link = jQuery(this).attr('href');
var $content = '.blogPostsWrapper';
var $nav_wrap = '.blogPaging';
var $anchor = '.blogPaging .nextPage a';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$.get(link+'', function(data){
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
$('.blogPostsWrapper .loader').remove();
$next_href = $($anchor, data).attr('href'); // Get the new href
$($nav_wrap).before($new_content); // Append the new content
$('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('.netxPage a').attr('href', $next_href); // Change the next URL
$('.blogPostsWrapper .blogPaging:last').remove(); // Remove the original navigation
});
});
}); // end ready function
Could you maybe try the following code? This is how I got this working on my own site.
replace:
jQuery('.blogPostsWrapper').load(link+' .post')
with:
$.get(link+' .post', function(data){
$('.blogPostsWrapper').append(data);
});
You should use jQuery append() to add the new posts without using the old ones.
jQuery load() Will replace the data found in your element . Quoted from jQuery API:
.load() sets the HTML contents of the matched element to the returned
data. This means that most uses of the method can be quite simple:

jquery .get download content fully before rendering

Is there a way to render content only after it's fully downloaded using AJAX/get/load with jQuery?
As it stands currently, the loader shows while the 'html' is being downloaded, but once that's done it starts rendering. There's lots of images in the html so they start loading independently after the render.
Is this good design practice? In my opinion once the loader disappears, everything should render 100%, but of course this will increase load time.
Can I achieve this without any 'hacks'?
$(document).ready(function() {
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$.get("moreProjects.html", function(datas){
$('#portfolio').append(datas);
}, 'html').complete(function() {
$('#loader').hide();
});
return false;
});
});
You could always store the data returned in a variable and then append it in the complete function:
var returnedData;
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$.get("moreProjects.html", function(datas){
returnedData = datas;
}, 'html').complete(function() {
$('#portfolio').append(returnedData);
$('#loader').hide();
});
return false;
});
Another option would be to use a hidden div container to load the content and then show on complete:
$('#clicks').click(function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
$('#portfolio').append("<div id='content' style='display:none'></div>");
$.get("moreProjects.html", function(datas){
$('#portfolio #content').append(datas);
}, 'html').complete(function() {
$('#portfolio #content').show();
$('#loader').hide();
});
return false;
});
Get the HTML, place it on your page or preload with JS, if placing it on your page the images can not be hidden if they are to be loaded, but they can be placed of screen.
When the images are loaded, move the HTML to your portfolio element.
The code below is just an example, not tested, and the load function will probably fire on the first image that is loaded, I think ?
If so you will have to count the images, place a load function on each image, and then show the HTML when all images have loaded, or you could try just attaching the load function to the last image in your HTML, but there is no guarantee that the last image in the markup is also the last to load, but it often is.
There could also be a problem with load if images are cached by the browser, if so you need to find another solution, or turn of caching in $.ajax!
$('#clicks').on('click', function(){
$('#portfolio').append("<div id='loader'><img src='images/loader.gif'/></div>");
var jqxhr = $.ajax({
type:'GET',
url: 'moreProjects.html',
datatype: 'html',
done: function(datas) {
$('<div id="somediv"></div>').append(datas)
.css({position: 'fixed', left: -5000})
.appendTo('body');
}
});
jqxhr.always(function() {
$('img', '#somediv').on('load', function() {
$('#loader').remove();
$('#portfolio').append($('#somediv').contents());
});
});
return false;
});
Check this link, the last post: Wait untill all images are loaded
In my opinion what you have to do is to save the html in a variable,
then filter out all the img tags and pass it to the _loadimages function
in the post i give you setting the complete callback.
Something like this:
var $retData = $(datas);
var $imgs = $retData.find('img');
_loadimages($imgs,function(){
$('#portfolio #content').append($retData);
});

Resources