Reloading everything but one div on a web page - ajax

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam

Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).

I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.

Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>

What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/

You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

Related

iframe replacement

I need to make a page with a sidebar on the left, and a search page on the right. I need to be able to perform a search and have the results appear without refreshing the content in the chat frame on the left. Ideally, I need these pages to be able to talk to each other so that a link from the frame on the left can invoke a search on the right. Right now I'm using PHP to handle the search functionality on the right, but I can use any language really.
I looked at iframes, but I was really hoping to have the "search" page be the main page so that the scrollbar in the browser reflects the position on the search page.
I also thought maybe this could be done with AJAX, but since my search box is a form, I wasn't sure how to pass parameters to the page that shows the results.
Hopefully this makes sense, I'll clarify what I can. Thank you!
You can still use ajax. Consider jQuery:
HTML Search Form:
<form id="searchForm">
<input name="searchterm" />
<input type="submit" value="Search" >
</form>
HTML Search Results Container:
<div id="searchResults"></div>
jQuery:
$('#searchForm').on('submit', function(e) {
var $form = $(this);
e.preventDefault();
$.ajax({
url : '/path/to/search.php',
type : 'post',
data : $form.serialize(),
success : function (data) {
$('#searchResults').html(data); // or parse out your data into HTML if it isnt already sent that way
}
});
});

Filtering the loop by category using Ajax in Wordpress

Well, I have been looking everywhere for hours and hours and it seems like there's so many ways to do this, since I have never used Ajax before and have little knowledge of havascript, its become too hard for me.
I have the loop on my front page (index) or wordpress and I want to have a filter, a dropdown menu with different categories, that when clicked, the only posts showing in that same screen are the ones from that category. I need the loop to be refreshed with ajax, so the whole page is still left intact while you use the filter.
this is what i have on my Index file:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1.2.6")</script>
<script type="text/javascript">
$(function(){
$('#main_cat').change(function(){
var $mainCat=$('#main_cat').val();
$("#sub_cat").empty();
// call ajax
$.ajax({
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_call&main_catid=' + $mainCat,
success:function(results)
{
// alert(results);
$('#sub_cat *').fadeOut(500);
$('#sub_cat + p').fadeOut(500);
$("#sub_cat").append(results);
$('#sub_cat').load('http://localhost:8888/public_html/wp-content/themes/twentyten-child/templateloop.php');
$('#sub_cat + p').fadeIn(1);
}
});
}
);
});
The dropdown with the categories goes like this:
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
So, the dropdown works, and it's supposed to ajax load a wp template file with a query filtering only one category (grabbed from the wp_dropdown_categories). And the loading works fine if I have a dummy text in the templateloop.php file, but when I have the wp query, nothing happens. the #sub_cat div, which is where the loop is located and was supposed to be switched by the template file just dissapears with all the post listing and im left only with the top half of the page (until where the #sub_cat div used to be).
There has been so much trial and error, ive tried with the query call in the template file, in the index file, in the functions, i never seem to get any result.
on my functions.php file ive got this:
function implement_ajax() {
if(isset($_POST['main_catid']))
{
echo '<?php $paged = (get_query_var("paged")) ? get_query_var("paged") : 1; query_posts("cat='.$_GET['maincatid'].'&paged=$paged"); ?>';
die();
} // end if
}
add_action('wp_ajax_my_special_ajax_call', 'implement_ajax');
add_action('wp_ajax_nopriv_my_special_ajax_call', 'implement_ajax');//for users that are not logged in.
and the query line i used to use before all this, in the index file is:
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("cat=1,2,3,4,5&paged=$paged"); ?>
i've tried using the wp_query but it's just going nowhere, i really need guidance. Any help is appreciated. thank you.
That is more complicated than it needs to be. You shouldn't need additional queries or AJAX at all. If you theme is using the post_class() function as it should be, your posts all have classes associated with your categories. These classes are the category name prepended with 'category-'-- 'category-uncategorized', for example. All you really need to do is show and hide posts based on those classes.
I haven't written anything specifically for your circumstance but I have done this with some very large search results-- sometimes 400 or more per page-- and it works quite well. Here is the idea: Use jQuery to watch your select menu. You want change. When the select changes, parse the information to work out the category (I don't know off hand what information wp_dropdown_categories() includes in its markup.), show() the selected category and hide() everything else.

Dynamically inserting content within same page rather then going to a new page

EDIT italics = more detailed explanation added to the question. Thanks.
I'm building a jQuery Mobile site which has a Gallery section.
The gallery has a series of thumbnails on the top of the screen.
Users click on the thumbnail to load in new content, that being a larger image, text, and potentially audio on some of them.
It's at this point that I'm not sure what to do: the way jQuery Mobile works, it's geared towards loading new pages, or views. But I just want to inject new content in a container on the current page.
To be clear, when the user clicks on another thumbnail, a new image replaces the content of the container with new content.
I have two questions:
I'm not sure how to structure the dynamic content. I was thinking i'd create an html file for each item, which as a rule always contains a title, information and sometimes, audio.
I'm not sure how to script this functionality in jQuery Mobile. It's obviously Ajax, but I'm not familiar with it yet, especially since jQuery Mobile has it's own methods in place already which seems to redefine behaviors in a way that's contradictory to this approach described here.
Here is a code explanation of what i'm trying to do:
<!-- Galleries -->
<div data-role="page" id="galleries">
<div data-role="content" role="main">
This is the Selection UI, if i click on thumb2.jpg, it'd
fill #content-holder with the whatever html is in content2.php
<div id="thumb-carousel">
<img src="thumb1.jpg">
<img src="thumb2.jpg">
<img src="thumb3.jpg">
<img src="thumb4.jpg">
<img src="thumb5.jpg">
<img src="thumb6.jpg">
<img src="thumb7.jpg">
<img src="thumb8.jpg">
<img src="thumb9.jpg">
</div>
<!-- This is the container, currently it's filled
with the kinda stuff i need to put in it. -->
<div id="content-holder">
<img src="myimage1.jpg"/>
<p>Artwork Title</p>
<p>Caption</p>
<audio>//mp3</audio>
</div>
</div>
</div>
//remember to use event delegation because you never know when the page will be in the DOM
$(document).delegate('#galleries', 'pageinit', function () {
//bind a `click` event handler to each thumbnail link
$('#thumb-carousel').children().bind('click', function () {
$.ajax({
url : $(this).attr('href'),
success : function (serverResponse) {
//select the container,
//then fade it out,
//change it's HTML to the response from the AJAX request,
//and fade it back in
$('#content-holder').fadeOut(500, function () {
$(this).html(serverResponse).fadeIn(500);
});
},
error : function (jqXHR, textStatus, errorThrown) {
//remember to handle errors so your page doesn't seem broken to the user
}
});
//prevent the default behavior of the link, which is to navigate to the `href` attribute
return false;
});
});
This expects your server-response to be valid HTML markup that is ready to inject into the DOM, meaning no <html> or <body> tags, just what you want to add to the DOM:
<img src="..." />
<span>TITLE</span>
<audio src="..."></audio>
Here are some docs for ya:
$.ajax(): http://api.jquery.com/jquery.ajax
.closest(): http://api.jquery.com/closest
.fadeIn(): http://api.jquery.com/fadein

JQuery for Push-down form

Is there a JQuery plugin that allows me to 'unhide' a form by after clicking a link? Like I have an invite link that can take me to a one text field form for an email address but I want this form to just drop down (pushing the rest of the content down also) and shows the form to submit the email. If you guys can think of a JQuery plugin that lets me do this, please let me know
Edit:
So I did this
<div class='add-link'>
<div id='invite_link'><a href=''>Invite User</a></div>
<div id='invitation_form'>
<form>
<input type='text'/>
</form>
</div>
</div>
and my jquery looks like
<script type="text/javascript">
$(function()
{
$("table").tablesorter({sortList:[[0,0],[2,1]], widgets: ['zebra']});
$('#invitation_form').hide();
}
);
$('#invite_link').click(function() {
$('#invitation_form').slideDown();
});
Do you guys see any error that causes the form not to slide down. It hides the form when the page loads but when I click the link it is not sliding down.
$('a.mylink').click(function() {
$('#MyForm').slideDown();
});
I don't think you need a jQuery plugin for this. The base jQuery library should be sufficient.
$('#showFormLink').click(function () {
$('#form').slideDown();
});
If you're looking for animation, that's possible as well by passing in a duration argument to slideDown.
Take a look at the jQuery show documentation.

How can I make an AJAX link work once it is moved out of the iFrame?

I am using an iFrame with a form that return some content with an AJAX link.
I am then moving the returned content out of the iFrame into the main page.
However, then the ajax link does not work and the error "Element is null" is created once the link is clicked.
How can I move content from the iFrame and still have the AJAX link working?
Here's the code returned by the iFrame:
<span id="top">
<a id="link8" onclick=" event.returnValue = false; return false;" href="/item_pictures/delete/7">
<img src="/img/delete.bmp"/>
</a>
<script type="text/javascript">
parent.Event.observe('link8', 'click', function(event) {
new Ajax.Updater('top','/item_pictures/delete/3', {
asynchronous:true, evalScripts:true,
onCreate:function(request, xhr) {
document.getElementById("top").innerHTML = "<img src=\"/img/spinner_small.gif\">";
},
requestHeaders:['X-Update', 'top']
})
}, false);
</script>
</span>
I see two problems with your code.
First the solution (I think :-))
When your iframe loads, the javascript in it runs. Javascript attaches an observer to parent document's link8.
Inside the observer you define another function (onCreate). This function will run in iframe context, making document object refer to iframe and not to main document. When you remove link8 from iframe to move it to main document, document.getElementById("top") will become null - hence error.
Perhaps change it to:
parent.document.getElementById("top").innerHTML = "<img src=\"/img/spinner_small.gif\">";
Second problem (that is not really a problem in this particular case) is, if you move whole span (including the script) to main document, the javascript will run again in main document's context. In your case, you should see an error or warning after you move the content, stating that parent is null (or similar).
To remove the second problem, return your iframe data in two divs or similar. Then copy only div with html to main document.
What I did was move the AJAX call out to an external js file and called the function once the link was clicked. It works now.

Resources