I've spent hours reading javascript books, patterns and looking on stackoverflow questions but I'm stuck on loading something dynamically into an iframe
Goal Click on a button, (1) ajax post to temp.php with data (ex. src, height, width, id).
(2) temp.php sets up the iframe and returns the respective html. (3) Javascript prepends the data.
Here is the respective code I have so far
(1)
$.ajax({
type:"POST",
data:{
'src':"target.php",
'frame_height':$(".mydiv").height(),
'frame_width':$(".mydiv").width()
},
url:"temp.php",
success:function (inHtml) {
loadConversation(inHtml,
I've loaded the POST variables into the respective php variables already.
(2)
<iframe id="myTestFrame" src="<?php echo $src; ?>" width="<?php echo $width; ?>"
height="<?php echo $height; ?>" frameborder="0">
<p>Your browser does not support iframes.</p>
(3)
$('.mydiv').prepend(inHtml);
Please assume that the syntax is done correctly.
the target.php does run a simple javascript code initializing a scroll plugin:
$(function () {
var Scroll = (function () {
var init = function () {
$("#content-1").mCustomScrollbar({});
$(".inner_content").mCustomScrollbar({autoDraggerLength:true});
$(".output a[rel~='_mCS_1_scrollTo']").click(function (e) {
e.preventDefault();
$("#content-1").mCustomScrollbar("scrollTo", $(this).attr("href"));
});
};
return { init:init };
})();
Scroll.init();
});
What's happening now is that I can call temp.php directly from the webserver and it will load properly.
expected
But once it's called from the main site - it breaks (and an 'undefined' to boot)
broken in main site
I've done the same iframe post and then update src dynamically with another php page with a plugin and it works fine (same on click, ajax post, prepend(html) , I'm completely lost). The main site is running it inside a tabbed interface from jquery UI, but I don't think that makes any difference - what I've found so far is that if I insert a simple 'alert(document.height)' into the init function, the alert box will contain 0, so I think the javascript runs before the iframe has finished loading - but Firebug shows that the Response HTML in NET is perfectly fine and the code is rather short. (The script is placed last right before the close brace)
Related
I am trying to load a static street view image, where the various parameters are stored in a mysql database. After trying lots of alternatives, I'm now passing the database data to a javascript variable and then trying to build the relevant URL (taking into account the page width along the way).
The page loads as restaurant.php?r=xyz where xyz is looked up on MySQL to return a line of data $r that is passed into a javascript array. Some of the array fields are used to create the URL of a Google Street view static image, which should then be loaded into the page.
This works fine if I enter the get to this page having started elsewhere on the site (or after a page refresh).
But if I start from this page and navigate around all future links to restaurant.php?r=abc do not load the image (it is downloaded and can be seen in the Chrome sources box). The pageinit event fires but the .html() fails to change the content (but reports no error).
I suspect I am breaking several laws of javascript, and jquery mobile....
Declared in header
var resto = {};
function insertSVPhoto() {
console.log("insertSVPhoto: Loaded data for: "+resto['rname']);
if ( Math.round(resto['heading']) != 0) {
var width = Math.round( $(document).width() * .9);
var s= "x250&location="+resto['lat']+",%20"+resto['lng']+"&fov=60&heading="+resto['heading']+"&pitch="+resto['pitch']+"&sensor=false";
var photo = "<img src='http://maps.googleapis.com/maps/api/streetview?size="+width+s+"'>";
console.log("Loading photo: "+photo);
$('#svphoto').html(photo);
} else {
console.log('No photo available');
$('#svphoto').html("<img src=''>");
}
}
And then below I have
<div data-role="page" data-add-back-btn="true">
<script type="text/javascript" >
<?php
echo "resto = ".json_encode($r).";";
?>
$( document ).on("pageinit", insertSVPhoto );
</script>
<div id='svphoto'></div>
I have to confess i'm no expert here but the way you're doing this doesn't seem quite right to me, i'd do the following:
window.onload = function () {
if(! window.device)
deviceReady()
}
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
$(document).delegate('#YOUR_PAGE_ID', 'pageshow', function () {
// Add your stuff here for doing the photo....
}
Again I only started using JQM a while ago but I know this works for an app i've done(and for a phonegap build too!)
EDIT: Also I would seriously consider putting everything all in one HTML document the way you've developed this is going to cause you a massive nose bleed if you try and build this as a mobile app, JQM is not designed to be used in the same way as Jquery, all of your "pages" should exist in one single html document and then use the navigation functions to move between pages.
Thanks
Marc
add data-ajax="false" or rel="external" to your links.. that should make it load properly
hello
OR
hello
I'm using Fancybox to load and Iframe with a form. After I post it, onsubmit calls "return onSubmitForm()"
<script type="text/javascript">
function onSubmitForm() {
parent.jQuery.fancybox.close();
window.parent.location.reload(true);
}
</script>
So Php/Smarty is loading the dynamic content OK in my database. I can also close the Iframe. BUT, after reloading the parent, it's dynamic content is not updated.
I have doing several tests and it only works occasionally (1 in 10). The previous content gets sticky.
I also started using "nocache" or "caching=0" (for PHP/Smarty variables). So far it doesn't help.
If I reload manually the browser, it works.
Thanks!
Diego
Inside the iframe (with the form) just try closing the box
function onSubmitForm() {
parent.jQuery.fancybox.close();
}
...then, in the parent page (from where you called fancybox) add this API option to your script... something like
jQuery(".fancybox").fancybox({
type: "iframe",
width: 640, // or whatever
height: 320,
afterClose : function() {
location.reload();
return;
}
});
I’ve created a “load more” link which loads the next 100 entries via a AJAX call.
My AJAX call looks like this:
<script type="text/javascript">
function HideButton(){
$('#load_post').css('display', 'none')
}
$.ajaxSetup ({
cache: false
});
var ajax_load = "<div class='loading_wrapper'><img class='loading' src='<?php echo url(); ?>images/ajax-loader.gif' alt='loading...' /></div>";
var loadUrl = "http://www.mydomain.com/loadmore.php";
$("#load_post").click(function(){
$("#result")
.html(ajax_load)
.load(loadUrl, {exclude: "<?php echo $exclude_more_post_str; ?>"},
function() {
$('#load_post').css('display', 'none');
});
});
</script>
The loadmore.php codes just retrieve the next 100 entries from the database, which is pretty much the same query as the main page just with an offset.
It loads correctly the 100 entries but it does not load it into my colorbox iframe. The first entries, before loading more via AJAX, works fine but the 100 entries loaded by AJAX don’t load the page inside the colorbox even though it has the right class attached to the a href.
When pressing an entry which should be opened in a colorbox iframe it just show the page, e.g. http://www.mydomain.com/single-entry/this-is-the-post-suppose-to-open-in-colorbox/
Is there some special property I have missed when running the AJAX call so I need to reload the colorbox. I’ve tried to but the Colorbox javascript in both the header and the footer but the result is the same.
If I’ve explained myself unclear, please let me know and I’ll try to clarify.
Sincere
- Mestika
If you want to show the content of loadmore.php, or other url, into a colorbox iframe try changing the href attribute of its plugin container (i.ex: <a class="loadmore" href=""/>... or whatever you call it) and throw the click event (if previously initialized).
$("#load_post").click(function(){
$(".loadmore").attr('href', "http://www.mydomain.com/loadmore.php").click();
});
You could even chain the initializing method over .loadmore tag like that:
$("#load_post").click(function(){
$(".loadmore").attr('href', "http://www.mydomain.com/loadmore.php")
.colorbox({iframe:true, width:"80%", height:"80%"}).click();
});
I hope it will
I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome
It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.
EDIT: This question was initially too general, I think. So What I really need is a very good tutorial on how to implement the Load More function on Safari for iPhone just like the Twitter website(mobile.twitter.com) does. Just a wordpress plugin won't really help. But if the plugin is well explained, like if it is wptouch, home(that also has this function) that can also do.
I know that it doesn't really matter that it is being displayed on a mobile device, but the point I am stressing is that if such a function is well explained, then it will be up to me to know how to customize it to suit me.
I am using a javascript function to load entries that come from the database dynamically, so that content opens in the same page (like with twitter(tweets feed) and facebook(news feed)).
The php/html version(That opens a page in a new tab) is
echo 'Load more entries› ';
The javascript/ajax version:
<div id="call_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>" class="ajax-load-more">
<img id="spinner<?php echo md5($_SERVER['REQUEST_URI']); ?>" class="spin" src="<?php bloginfo('template_directory'); ?>/images/main-ajax-loader.gif" style="display:none" alt="" />
<a class="ajax" href="javascript:$ajax_hv('#spinner<?php echo md5($_SERVER['REQUEST_URI']); ?>').fadeIn(200);
$ajax_hv('#ajaxentries_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>').load('form='<? echo $form_id; ?>&page=<?php echo $page+1;?>', {},
function(){ $ajax_hv('#call_hv<?php echo md5($_SERVER['REQUEST_URI']); ?>').fadeOut();})">Load more entries...
</a>
The basic idea is to listen to scroll events, and implement paging on the server side.
A scroll event is fired whenever the document or a contained HTML element scrolls. I'll use this sketch for reference keeping the following things in mind:
Let's say the height of the browser window is 800px, and the initial height of the content is 2500px. The threshold for loading AJAX content is when the user scrolls to the bottom 100px of our content (after the first 2400px).
We will need to keep track of the following 2 items:
Items/Pages loaded so far.
How far are we from the bottom of
the page.
The code references are in MooTools, but the concept is the same. Converting it to jQuery is a trivial task once you understand it.
var maxPage = 1;
var threshold = 100;
We need to know whenever the page scrolls, so add a handler for scroll events. Find the scroll distance to the bottom of the page. If it's less than the defined threshold (100px), then fire off an AJAX request loading the next page. When the response comes (if successful), append it to the page and increment maxPage number.
Another thing to keep in mind is to only fire an AJAX request if content is not already being loaded. Have a flag that indicates whether the page request is still pending.
var isLoading = false;
window.addEvent('scroll', function() {
// the height of the entire content (including overflow)
var contentHeight = window.getScrollSize().y;
// current scroll is height of content that's above the viewport plus
// height of the viewport.
var contentScrolled = window.getScroll().y + window.getSize().y;
var distanceToBottom = contentHeight - contentScrolled;
var closeToBottomOfPage = distanceToBottom < threshold;
var shouldLoadMoreContent = !isLoading && closeToBottomOfPage;
if(shouldLoadMoreContent) {
// create an ajax request
var request = new Request({
url: 'http://www.example.com/more',
onSuccess: function(responseText) {
$('page').append(responseText);
maxPage++;
},
onRequest: function() {
isLoading = true;
},
onComplete: function() {
isLoading = false;
}
});
// fire off ajax request with the page # as a querystring param
request.send({page: maxPage});
}
}
Commonly called an Infinite scroll. There are plugins for jQuery and Wordpress:
http://www.infinite-scroll.com/