jQuery mobile: Dynamically add image - php

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

Related

Loading pages into div via ajax navigation - Couple of problems

I'm new to this whole programming business and I'm trying to put together a simple website for myself.
At present the website has a header, some navigation links, a makeshift image below the nav(which will be amended later and isn't relevant to the question much), and below that I have 3 content divs. The main content div, and two more to the right of it which I'm intending to be my sidebar widget for maybe a twitter feed, ads, that sort of thing.
I've set up the navigation links so that external pages are loaded inside my left-col div(my main content area). The Ajax works grand, as it is, it does exactly as was said on the tin.
The issue is each nav link reads javascript:ajaxpage('pageaddress.php','left-col');
Couple of things I don't like about that:
When you refresh the page it will naturally load the index.php content
Because the website address remains the same throughout browsing. It doesn't change to, let's say, /About.php.
Also, this doesn't work out well for SEO. Assuming I want individual page addresses, titles, and what not - and I do.
There is no real problem with the script, it works sure enough, it just doesn't work how I want it to work. Here's the Ajax script anyway.
<script type="text/javascript">
/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}
</script>
and here's and example of a navigation link
<ul id="nav">
<li>Design</li>
Is there a way I can alter the Ajax so that each page loads inside the div, while also changing the url, allowing me to have different titles for each page, and also preventing the website from loading the index.php on refresh?
If not, does anyone know of any other scripts of methods of loading pages - and it doesn't necessarily have to be ajax - into a div only while doing what I want it to do(diff urls, titles, etc,)
This is my first time posting so hopefully my question is clear enough - albeit long - and is formatted properly.
Thanks, Chris.
For easy Ajax handling you can use for example jQuery.
But that doesn't change anything about the "changing the url" problem. For that you should use hashes (#). Your urls would look like index.php#about or ../#about. You can check that string after the # and show an individual page.
var hash = "default.html";
if(window.location.hash)
hash = window.location.hash.substring(1);
switch(hash){
case "default":
showPage(1);
break;
case "news":
showPage(2);
break;
// ...
}
Take a look at this question Redirect all website traffic to PHP handler, pitfalls?
In the handler (index.php) you can set title, content (include) base on $_SERVER['REQUEST_URI'].

saving and loading the ajax state of a page

I'm working on an ajax loading function on a Wordpress single page portfolio.
The principle is that when you click a thumbnail in the gallery, it opens a container (#DrawerContainer) and fetch the ajax content of this article into it. With a lot of help, I'm already able to open the drawer and load the post content when I click a thumbnail.
Here is a fiddle if you want to see it working (the ajax will not load but it works locally). http://jsfiddle.net/RF6df/24/
The part I'm working on now: I need my site to be crawlable and the urls to be shareable. If I give http://mywebsite.com/#!project5 to someone, I need project5 content to be opened when he loads the page.
I thought the hash-bang (#!) urls was the way to go to make this work. With the code below (commented on the jsfiddle), I can update the url and add the hash of the clicked thumbnail.
var pathname = $(this).find('a')[0].href.split('/'),
l = pathname.length;
pathname = pathname[l-1] || pathname[l-2];
window.location.hash = "#!" + pathname;
But when I load a page, the ajax state isn't remembered. I assumed it was because my ajax container was only loaded on click event, but there is no change when I add a persistant container in the php.
Is there a way to load the page with a post content already displayed, or to open the #DrawerContainer when the page is loading a hash-bang url?
Please keep in mind that I'm just learning jquery and ajax. So I'd really appreciate if you explain or comment a little bit what you do, I'll for sure learn at the same time... :)
on onload you should check the window.location.hash and trigger a click on the particular link/div.
$(document).ready(function() {
var hash = window.location.hash;
if ( hash.length > 0 ) {
hash = hash.replace('#' , '' , hash );
$('a[rel="'+hash+'"]').trigger('click');
}
});
I have used the following on sites where I want to trigger via hash changes.
First I bind a hashchange event to get the hash value
$(window).bind('hashchange', function(o){
url = window.location.hash.substring(1);
o.preventDefault();
if (!url) {
return;
}
}
Then I trigger the hashchange when I want - in your case when the page loads i.e. on document ready.
jQuery(document).ready(function($) {
$(window).trigger('hashchange');
});
You can then use the hash value in your function that loads the correct content

Load html with ajax, but hide content until loaded

I'm using jQuery to load content dynamically when the user clicks a link. The content is just a bunch of images that are then set to display in a slideshow of sorts. My problem is, I can't seem to figure out a way to show the loaded content only AFTER the images have fully loaded. I've tried several different solutions and all of them seem to either break the script or just not work the way I want. Here's the code I'm using now:
$(document).ready(function() {
$("a#item").click( function() {
var projectName = $(this).attr('class');
$("div.slideshow").css("display", "block");
$("div.slideshow").load(projectName+".php", function() {
var slideshow = new Array();
$("div.slideshow img").each(function() {
slideshow.push($(this));
});
startSlideshow(slideshow.shift());
function startSlideshow(image) {
image.delay(400).fadeIn(150, function() {
if(slideshow.length > 0) {startSlideshow(slideshow.shift());}
else { $("div.slideshow").delay(400).fadeOut(200, function() {$("div.slideshow img").css("display", "none")}); }
});
}
});
return false;
});
});
You can also see the full demo site here: http://publicprofileproject.com/
Any input would be greatly appreciated!
You could create an array of image objects in your JavaScript, loading each image into an element of the array. Attach an event handler to the onLoad event of the images.
In the event handler, increment a count of loaded images. When your counter reaches the length of your array, the browser will have all of the images. This is the point at which you can show your slideshow.
If you do this in your page load, it will have the added advantage of pre-loading the images ready for when the user clicks your link.
I believe this question has already been answered here.
The general idea is that you specify a load event handler to display it prior to specifying the source attribute.
Alternatively, if your projects+".php" file is specifying the images in ready-made, html mark-up, then you should be able to capture the load event of the images in the file you are loading. Add the following pseudocode into your file that is being loaded.
$("img").load(function() {
// show the div on the page it is getting loaded into
alert("images should be loaded now");
});
You might be able to place it in your original code segment and potentially bind it using the live / on binding events. ex: $("img").on("load", function() {...
From the load documentation:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
Edit: Interesting discouragement for doing what it looks like you're doing:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

Load div from another page within an AJAX loaded page

I'm using jQuery address to enable loading specific content from other pages
and to change the URL in the address bar.
I'm working on a little Social Network alike website, so I'm reading out the IDs
of the posts table of my MySQL database via PHP. I want to use the possibilities of jQuery and AJAX to read everything out dynamically.
I found out, that I have to use live() (which turned out to be old), delegate() (which
also turned out to be old in 1.7.1) or on() (which turns out to be the best possibility
to make events work inside of dynamically loaded content via jQuery + AJAX).
I also read somewhere, that I can't use load() or get() to load new content from another
page inside of an already loaded content, because it doesn't "bubble" (I don't even know
what that means).
What do I have to do to load new content within an AJAX loaded page?
Here's a snippet I tried to work with (included on the loaded page):
<?php
if(exist('`posts`')) {
$load = mysql_query('SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 10');
while($row = mysql_fetch_object($load)) {
?>
<script type="text/javascript">
$('body').on('body', 'load', function() {
$.get('getpost.php', { pid: <?= $row->id ?> }, function (data) {
$('#posts').html($('#post_<?= $row->id ?>', data).html()).show();
});
$('#posts').off('load');
});
</script>
<?php
}
}
else {
?>
<div align="center">No posts yet.</div>
<?php
}
?>
getpost.php is my file from which I can get the div_$row->id so that it appears on the start page.
PLUS (Just adding for your knowledge) I want the content to load the content without
a mouseover, click or blur event.
Thanks.
You want to use ".live()" if you want a particular event mapping to be applied dynamically to any new DOM elements which match its selector. Alternatively, you can attach the behavior to each chunk of content loaded.
Write and develop your ajax load independently of your DB lookup to make things simpler. The following snippet triggers another ajax call after each element loads.
<?php
$id = 'div'.mt_rand();
$counter = isset($_REQUEST['counter']) ? $_REQUEST['counter'] : 0;
$next = $counter + 1;
echo <<<END
<div id="{$id}">{$counter}
<script>
$(function() {
$.ajax('/url?counter={$next}', function(html) {
$(html).appendTo($('#{$id}').parent()); // or whatever your favorite method is for adding a sibling
});
});
</script>
</div>
END;
?>
Am I the only one who thinks that this approach is completely wrong? You're making an ajax request for each post, this could end up in making way too much requests, heavily slowing down the loading time. I can't see any reason why you don't want to directly write the posts' HTML inside the PHP while loop.

Include Jquery script in .js page

Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file

Categories