Dynamically resizing an iframe that uses AJAX - javascript

I am attempting to dynamically resize an iframe. This wasn't too hard, until I changed the iframe page to use AJAX with jQuery. I am attaching a function to the iframe body's resize event that should resize the iframe as well. It seems that after it started using AJAX it would no longer trigger the resize event.
Here is the code I have in the parent site:
$(function(){
var iframe = $('#myiframe');
iframe.load( function() {
var iframe_content = iframe.contents().find('#content');
iframe_content.resize( function() {
var elem = $(this);
var newHeight = elem.height();
// Resize the iframe.
iframe.css({ height: newHeight });
});
// Resize the iframe immediately
iframe_content.resize();
});
});
Here is the AJAX form in the iframe site:
<form onsubmit="jQuery.ajax({type: 'GET',
data: $(this).serialize(),
url: '/employeedirectory/employee/ajaxUpdate',
success:function( data, textStatus ) {
$('#results').html(data);
// Go to the parent document, find the content div, and call its resize event
$(document, parent.window.document).contents().find('#myiframe').contents().find('#content').resize();
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {} });
return false;"
id="searchForm">
</form>
If I run $('#myiframe').contents().find('#content').resize() on the parent site to force the resize event then it works just fine. But it doesn't appear that it is calling that onsuccess like I want. Does anyone have any ideas?

Related

Event listener if div is reloaded

In some AJAX query, in response.done I refresh some div and it works fine, the problem is this refresh doesn't refresh also another function(this function fill the content html() of another div inside the refreshed one). I'm thinking for a trick to add an event to listen when that div is reloaded, I lunch my getAmount() function.
I tried to add that function after reloading part in AJAX but it doesn't work.
file1.phtml
ajaxRequest = jQuery.ajax({
...
ajaxRequest.done(function (response, textStatus, jqXHR) {
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table"); //Here I reload my div.
});
file2.phtml
function getAmount() {
var some = jQuery(this).attr('data-subtotal');
jQuery('#shopping-cart-table .data').each(function(){
jQuery('.ship-cart-vendor-header').each(function(){
jQuery(this).find('.not-reached').html(some);
});
});
}
You've to call your getAmount function in the load callback, what mean after the complete reloading :
jQuery("#shopping-cart-table").load(location.href + " #shopping-cart-table", function(){
getAmount();
});

onbeforeunload doesn't fire

I have an onbeforeunload event which should fire when I leave the page and run the code I have attached to that event. I have placed this within the scripts tag of the cshtml in my page, so in theory it should only fire if I am on that particular page and move off it(my understanding of the event could be incorrect). However when I go to another page the onbeforeunload event does not seem to want to fire. I have tried setting a breakpoint on it but does not seem to hit it and am not getting any errors on my console in firebug.
I have looked at this post which one of the posters mentioned using this event to detect a page change
Best way to detect when a user leaves a web page?
<script type="text/javascript">
$(document).ready(function () {
window.onbeforeunload = SaveDashboard;
});
function SaveDashboard(){
var gridArray = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var gridID = el.find('.grid-stack-item-content.ui-draggable-handle').first().attr('id');
var node = el.data('_gridstack_node');
return {
id: gridID,
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
$.ajax({
url: 'Dashboard/EditWidgets/',
type: 'PUT',
data: {
widget: gridArray
},
success: function (dataset) {
},
failure: function (xhr, error) {
console.log(xhr)
console.log(error)
},
});
}
</script>
you should return a string in the onbeforeunload handler. if you don't return anything, the event won't fire your handler. the text you have to return is the text that will be placed in the prompt the browser will open asking if the user really wants to leave the page.

Open javascript popup after jquery response

I have this simple javascript function:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.check', function(){
$.post('/index.php',
{
article: '1'
},
function(data, textStatus)
{
window.open('https://google.com');
});
});
});
</script>
<button class=".check">Check</buttton>
Although the click is user initiated but the popup is getting blocked by browsers. How to avoid this?
There's no way to unblock it through code.
Most browsers feel popups are very interrupting and that's the reason they block it.
You can only find out if the popup is being blocked and promptly notify the user to unblock it.
var wind = window.open('https://google.com');
if(!wind || wind.closed || typeof wind.closed=='undefined')
{
//POPUP BLOCKED
alert("please enable popups");
}
Your pop-up should be triggered directly by user interaction. But instead it's in an AJAX callback.
So, to prevent the block you should open the pop-up within the click handler. Then make the post..
EDIT: A tricky method would be to open the popup directly, then make the request and finally redirect the popup to the result URL:
$(document).on('click', '.check', function(){
var popup = window.open('/loading.html', 'popup');
$.post('/index.php', { article: '1' },
function (data, textStatus) {
popup.location.href = 'http://new-url';
});
});
You can try this trick:
function(data, textStatus)
{
var anchor = $( '<a/>', {href:'https://google.com',target:'_blank'} ).text( 'TEST' );
$('body').append( anchor );
$('body').find( 'a' ).last()[0].click();
anchor.remove();
};
JS FIDDLE DEMO

Close dialog box from within AJAX loaded content

I have a jquery ui dialog that loads its content via ajax:
$('#register').click(function(e) {
var tag = $('<div></div>');
$.ajax({
url: 'signup.html',
success: function(data) {
tag.html(data).dialog({modal: true}).dialog('open');
}
});
e.preventDefault();
return false;
});
I have a second script within the content that is supposed to close the dialog when the submit button is pressed
$(function() {
$('form #submit').click(function(e) {
$(this).parents('.ui-dialog').dialog('close');
e.preventDefault();
return false;
});
});
When i click the submit button, i get the error:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
What is it that i am missing to allow me to close the dialog from the content that has been loaded via ajax?
You have to call dialog('close') on the element where dialog('open') was called before. You're calling the function on$('.ui-dialog')instead of$('.ui-dialog ...')`.
You should define id or class for the tag element in your code:
var tag = $('<div id="signup-id"></div>');
Then find the correct element in click handler like this:
$(this).parents('.ui-dialog').children('#signup-id').dialog('close');
Note: You can find #signup-id in click handler directly like $(this).children('#signup-id') if you're sure that signup.html never contains element with signup-id id.
Define you tag dialog in html
<div id="tag_dialog" style="display:none">
</div>
then on document ready:
$(document).ready(function(){
$('#tag_dialog').dialog({
modal:true,
autoOpen:false,
//you could give some other options such as width, height .....
});
$('#register').click(function(e) {
$.ajax({
url: 'signup.html',
success: function(data) {
$('#tag_dialog').html(data).dialog('open');
}
});
e.preventDefault();
return false;
});
$('form #submit').click(function(e) {
$('#tag_dialog').dialog('close');
e.preventDefault();
return false;
});
});

IFrame OnReadyStateChange function

I have an asp.webforms application and on page a i have a hidden div with progressbar and iframe. To iframe i try loaded form from another application on same domain.
<div id="pagePreview" style="display: none;">
<div class="progressBarWrapper" id="waitDialog" style="opacity:1;filter:alpha(opacity=100);display:none;">
<div class="progressBarDetail" style="margin-top:25%;">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/wait.gif" />
</div>
</div>
<iframe id="previewContent" onreadystatechange="iframeLoaded(this);"></iframe>
</div>
On a click event i call a function to show this div in jqueryUI dialog and i Want show progressbar until the page in Iframe is not loaded.
var isClickedForDialog = false;
function iframeLoaded(args) {
if (args.readyState == "complete" && isClickedForDialog) {
var pagePreview = $('#pagePreview'); // dialog
var waitDialog = $('#waitDialog'); // progress
waitDialog.hide();
isClickedForDialog = false;
}
}
function showModalWindow(url, hideCloseButton) {
isClickedForDialog = true;
var previewContent = $('#previewContent'); // Iframe
var pagePreview = $('#pagePreview'); // dialog
var waitDialog = $('#waitDialog'); // progresss
waitDialog.show();
previewContent.attr('src', url);
pagePreview.dialog(
{
draggable: false,
resizable: false,
height: 764,
width: 1020,
modal: true,
close: function (event, ui) {
previewContent.attr('src', '');
},
open: function (event, ui) {
if (hideCloseButton) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
}
}
});
}
In IE everything works fine. The dialog box and progressbar displays and when the URL is loaded in an iframe, progressbar disappears and i see only webforms in IFrame.
But in FireFox and Chrome this does not work.
The browser ignores the onreadystatechange event. I tried to handle an event as following:
$('#previewContent').bind('onreadystatechange', iframeLoaded, false);
$('#previewContent').on('onreadystatechange', iframeLoaded);
but without success.
know how to solve this? thanks
I'm not sure if there's some specific reason why you're using onreadystatechange, but if you just want to know when the iframe is done loading, the load event will handle that.
$('#previewContent').on('load', iframeLoaded);
Adding the onreadystatechange attribute to an iframe tag as shown in the original question doesn't seem to do anything. Don't do this:
<iframe onreadystatechange="iframeReady(this);"></iframe>
Instead, grab a reference to the iframe element and add a DOMContentLoaded listener to its contentDocument property. Since your iframe might already be fully loaded, you should check its contentDocument's readyState and cancel the listener if the iframe isn't loaded yet. Finally, some browsers - namely Firefox - don't currently emit a DOMContentLoaded event from iframes, so for a fallback you could add a load listener on the iframe's contentWindow property, or the iFrame itself.
function listenForIframeReady() {
if (iframe.contentDocument.readyState === "interactive" || iframe.contentDocument.readyState === "complete") {
iframeReady();
} else {
iframe.contentDocument.addEventListener('DOMContentLoaded', iframeReady);
iframe.contentWindow.addEventListener('load', iframeReady);
iframe.addEventListener('load', iframeReady);
}
}
function iframeReady() {
console.log('iframe is ready');
iframe.contentDocument.removeEventListener('DOMContentLoaded', iframeReady);
iframe.contentWindow.removeEventListener('load', iframeReady);
iframe.removeEventListener('load', iframeReady);
}
var iframe = document.querySelector('iframe');
listenForIframeReady();

Categories