jQuery Reload div onclick - javascript

Trying to make jQuery reload a .php file I have in my directory whenever I press a certain button.
(function($)
{
$(document).ready(function()
{
$('.loadimg').hide();
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('.loadimg').show();
$('#loadunasreports').hide();
},
complete: function() {
$('#loadunasreports').show();
$('.loadimg').hide();
},
success: function() {
$('#loadunasreports').show();
$('.loadimg').hide();
}
});
var $container = $("#loadunasreports");
$('#reloaddata').click(function() {
$container.load("unasreport.php");
});
});
})(jQuery);
When I press #reloaddata it shows and hide the div as supposed to, but it doesn't reload the php file in that div. However if I make it load dynamicly every 10 seconds for example then it works, but that's not what I want.
So how should I do?

Related

Click on the button after the class appears in the DOM

There is a form in the popup window that sends data to Ajax. After a successful form, a message about successful submission with the .form-message--success class appears below. I would like that when this class appears in 5 seconds, the window close button with the id #close_pop a is clicked.
Is this possible when a class is added dynamically to the DOM?
I tried something like this, but it doesn't work(
jQuery(document).ready(function($) {
$('.jet-form-message--success').on(function(){
setTimeout(function(){
$('#close_pop a').click();
}, 2000);
});
});
<script>
$(function() {
$("#user-form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "form.php",
method: "POST",
data: $( this ).serialize(),
success: function(data) {
alert('form send success');
setTimeout(function(){
$('#close_pop a').click();
}, 2000);
},
error: function(xr) {
alert("error "+xhr.status+' '+xhr.statusText);
}
});
});
});
</script>

Loaded content and javascript asynchronous issue

I replaced content from index.htm with content from project.htm. When you click on a#front it is linked on project.htm and it dynamically loads (replaces) the new content. But I have an issue with how to execute javascript that I'm loading with new content. To load script I used function getScript. Here is the function that I'm using to load new content and script:
$(document).ready(function() {
$('a#front').click(function() {
var toLoad = $(this).attr('href')+' #content';
$('#content').hide("drop", { direction: "left" }, "slow", loadContent);
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad ,'',showNewContent())
}
function showNewContent() {
$('#content').show("drop", { direction: "right" }, "slow");
$.getScript('js/project.js');
}
return false;
});
});
Javascript that I loaded when I loaded new content only worked if I had alert at the top or this way. But when I try to load more complex content (insted just text I put div, headings etc) it doesnt work:
$.ajax({
success: function(data) {
$('a#link').click(function() {
$("p").css("color","white");
});
}
});
Can you help me with this or maybe you have some different solution?
I solve this problem and menaged to load content from new file and also javascript for that. Notice that in new file I need to have content wrapped into div with ID content and I load it into div in native document, with the same name - content.
Here is how I load new content and how I call new javascript files using getScript function:
$('a#front').click(function() {
var toLoad = $(this).attr('href')+' #content';
$('#content').hide("drop", { direction: "left" }, "slow", loadContent);
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad ,'',showNewContent())
}
function showNewContent() {
$('#content').show("drop", { direction: "right" }, "slow");
$.getScript('js/project.js');
$.getScript('js/section.js');
$.getScript('js/carousel.js');
}
return false;
});
To force loaded javascript execution I used setTimeout function. For example this is how looks code inside carousel.js file which activate carousel:
$(document).ready(function($) {
setTimeout(function(){
//run carousel
$("#owl-example").owlCarousel();
}, 100); });
How it works you can see here

Close jquery dialog from iFrame with external html

I am trying to close a jQuery ui dialog from an iframe with an external html inside.
My code looks like the following:
JS code in my main html to create the dialog when I click on a button:
function createDialog() {
return $("<div id='personal-popup' class='dialog' title='Copia de archivos'></div>")
.html('<iframe style="border: 0px; " src="copy.html" width="100%" height="100%"></iframe>')
.dialog({
resizable: true,
height: 447.59999990463257,
width: 993.5999999046326,
modal: true
});
}
JS code inside the other html (copy.html)
function copiarArchivos() {
$.mobile.loading('show',{
text: "Copiando",
textVisible: true,
theme: "a",
html: ""
});
var result = [];
var allOptions = $("#select-custom-19");
$("#select-custom-19 option:selected").each(function () {
var $this = $(this);
var selText = $this.text();
$this.prop("selected", false);
result.push(selText);
});
allOptions.selectmenu('refresh', true);
$.ajax ({
url: "php/copia.php",
type: "post",
data: {"params": result},
success: function(response) {
$.mobile.loading('hide');
//I want to close the dialog here when the ajax function success
$(window.parent.document).find("#personal-popup").dialog('close');
}
});
}
I have followed the answer to this question: Close jQuery UI Dialog from Iframe, but it didnĀ“t work for me.
--- EDIT ---
The JS function which is going to be called from the iFrame, allocated in the mane html (index.html)
function closeDialog(){
console.log("Im working!!");
document.getElementById("personal-popup").dialog("close");
}
The JS call from the iframe (copy.html)
$.ajax ({
url: "php/copia.php",
type: "post",
data: {"params": result},
success: function(response) {
$.mobile.loading('hide');
window.parent.closeDialog();
}
});
from inside the iframe you can access window.parent.
This means that in your main frame you could have:
window.closeDialog = function(){//Do stuff}
Anf then in your iframe have:
window.parent.closeDialog();

tumblr audio + Masonry with infinite scroll- other solutions posted have confused me [duplicate]

Here's a test page: http://masonry-test.tumblr.com/
I'm using jquery Masonry with infinite scroll on tumblr. All is fine except with audio players. They won't load on the second page and display this message instead [Flash 9 is required to listen to audio.].
Did a little research and found a solution. One here (this one too) and here's the js from the Mesh theme that does that successfully (line 35).
Problem is I don't know where and how to implement it in my code. Everything I tried either wasn't working or it left a small gap around the masonry blocks. My code:
$(document).ready(function () {
var $container = $('.row');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector: '.post',
columnWidth: 1
});
});
$container.infinitescroll({
navSelector: '#page-nav',
nextSelector: '#page-nav a',
itemSelector: '.post',
loading: {
finishedMsg: "No more entries to load.",
img: "http://static.tumblr.com/7wtblbo/hsDlw78hw/transparent-box.png",
msgText: "Loading..."
},
debug: true,
bufferPx: 5000,
errorCallback: function () {
$('#infscr-loading').animate({
opacity: 0.8
}, 2000).fadeOut('normal');
}
},
function (newElements) {
//tried this but doesn't work
/* repair video players*/
$('.video').each(function(){
var audioID = $(this).attr("id");
var $videoPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$videoPost.append('\x3cdiv class=\x22video_player_label\x22\x3e' + data.posts[0]['video-player'] +'\x3c/div\x3e');
}
}
});
});
/* repair audio players*/
$('.audio').each(function(){
var audioID = $(this).attr("id");
var $audioPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$audioPost.append('\x3cdiv class=\x22audio_player\x22\x3e' + data.posts[0]['audio-player'] +'\x3c/div\x3e');
}
}
});
});
var $newElems = $(newElements).css({
opacity: 0
});
$newElems.imagesLoaded(function () {
$newElems.animate({
opacity: 1
});
$container.masonry('appended', $newElems, true);
});
});
$(window).resize(function () {
$('.row').masonry();
});
});
By default the API will return a white audio player.
you can change it by using the jQuery method to replace the flash player with a black or white player respectively.
.replace("audio_player.swf", "audio_player_black.swf")
or simply change the color itself
.replace("color=FFFFFF", "color=EA9D23");
Example:
$('.audio').each(function(){
var audioID = $(this).attr("id");
var $audioPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$audioPost.append('\x3cdiv class=\x22audio_player\x22\x3e' + data.posts[0]['audio-player'].replace("audio_player.swf","audio_player_black.swf") +'\x3c/div\x3e');
}
}
});
I had a lot of trouble with this and hope it helps someone out. I found the above information here Change Tumblr audio player color with Javascript.
I noticed a few things and this is what I advise you to try:
For that script to work, the elements with the class "audio" should each have an "id" attribute with the post ID. The HTML should look like that:
<div class="audio" id={PostID}>{AudioPlayerWhite}</div>
Tumblr will automatically fill the {PostID} part with the ID for each post. I suppose it works in the same manner for videos (haven't tried it with videos yet).
As for position, I did it like this:
function (newElements) {
....
$newElems.imagesLoaded(function () {
....
});
//audio repair goes here!
}
Here is a solution I came up with when I needed to implement the same functionality in the template I was creating.
In your HTML, include your AudioPlayer Tumblr tag between comments. This is to prevent loaded scripts from being called. Also add a class "unloaded" to keep track whether or not we've loaded the audio player for this post or not.
...
{block:AudioPlayer}
<div class="audio-player unloaded">
<!--{AudioPlayerBlack}-->
</div>
{/block:AudioPlayer}
...
If you look at the commented code after the page is loaded, you will notice an embed tag being passed to one of the Tumblr javascript functions. Since we commented it, it will not execute. Instead we will want to extract this string and replace the div contents with it.
Create a javascript function which will do this. This can be done with regular javascript, but to save time I will do it with jQuery since this is how I did it for my template:
function loadAudioPosts() {
// For each div with classes "audio-player" and "unloaded"
$(".audio-player.unloaded").each(function() {
// Extract the <embed> element from the commented {AudioPlayer...} tag.
var new_html = $(this).html().substring(
$(this).html().indexOf("<e"), // Start at "<e", for "<embed ..."
$(this).html().indexOf("d>")+2 // End at "d>", for "...</embed>"
);
// Replace the commented HTML with our new HTML
$(this).html(new_html);
// Remove the "unloaded" class, to avoid reprocessing
$(this).removeClass("unloaded");
});
}
Call loadAudioPosts() once on page load, then every time your infinite scrolling loads additional posts.

event.preventDefault not working. Ajax call causing this?

I'm trying to use scrolltop method and event.preventDefault is not working properly.
What I'm experiencing is that the page scrolls UP first then scrolls down.
It seems that The onclick causes the page to resubmit or something... (ajax post??)
I have following code
button (trigger)
<a id="nextset" class='nextbtn' >Next Step</a>
event
jQuery('#nextset').click(function (event) {
event.preventDefault();
movenext('set');
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 2000);
});
functions
function getfav(obj) {
var myParams = "{ 'proattr':'" + obj + "'}";
jQuery.ajax({
type: "POST",
url: "project.aspx/getproject",
data: myParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () { jQuery('#wait').show(); },
complete: function () { jQuery('#wait').hide(); },
success: function (msg) {
GetProjectPic(msg.d, obj); //creates DOM and insert in div
Initbtns();// dynamic btns initialization
}
});
}
function movenext(obj) {
//other codes to hide/show DOM
getfav(nextobj);
}
If I add return faulse; in onclick event, the button doesn't work.
Any idea what's causing the scrolling to the top?
UPDATE:
It was caused by code block inside movenext function.
jQuery('[id^="favdiv"]').empty();
nothing to do with event.preventDefault.
The strange thing is that the screen scrolls much more than hidden div height ("favdiv") which causes up and down screen effect. I'm not sure how to prevent it...
UPDATE2
I searched jquery empty method and found this.
jquery "empty" changes the scrollbar
You can avoid the default behaviour by using the following snippet:
<a id="nextset" class="nextbtn" href="javascript:void(0);">Next Step</a>
Did you by any chance try putting "return false" at the end of your click event?
jQuery('#nextset').click(function (event) {
movenext('set');
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 2000);
event.preventDefault();
return false;
});
I end up writing something like this. still it goes up a bit but at least page doesn't jump
jQuery('#favdiv' + obj).fadeOut('fast', function () {
jQuery('#favdiv' + obj).remove();
});
setTimeout(function () {
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 1500);
}, 500);

Categories

Resources