Jquery Ajax loading the whole page except a certain div - javascript

I am writing an app that has an audio player at the footer. each Time i click on a link whole page itself loads thus the audio player is being restarted, my question How would you reload the whole page except a certain div?

I believe that is not possible. Maybe change your approach. Reload only specific areas you want to refresh. In fact, these areas may be included in a single (and possibly big) div tag. Then you can just update that div using jQuery ajax. For that, load is the way to go:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
Edit:
Here is a more specific example using links (just wrote it off of my head):
<script type="text/javascript">
$(function(){
$("#myLink").click(function(event){
$("#updateThisDiv").load($this.attr('href'), function(){
alert('div updated!');
});
return false; // or event.preventDefault();
});
});
</script>
And your link would look like this:
<a href='pathTo/Page' id='myLink'>Link text</a>
...
<div id="updateThisDiv"></div>

So you are using jQuery ajax. Even you reload whole div by ajax, the audio object remains same. So you can again generate your audio progress with the help of the object.
EDIT:
Just suggestion if you are reloading your page.
First save the currentTime of your audio object on your session or even database using ajax. And when user load that audio, start with that currentTime.
you can do this something like this:
yourAudioObject.addEventListener(
'timeupdate',
function() {
$.ajax ({
type:'get',
url:'your/path/?currenttime='+yourAudioObject.currentTime,
......

Related

Jquery - Targeting elements that have been changed after page load

I have not been able to find any discussion of what I'm struggling with on this site or any other, but perhaps I'm not asking the right question. I'm working on a web interface for a wireless speaker powered by the raspberry pi, and (as I inherited it) almost all the POST requests are done with calls to $.ajax. $().ready() is as follows:
$().ready(function (){
$(document).ajaxStart(function (){
$.blockUI({ message: '<img id="loadimg" src="img/loading.gif" width="64" />'});
}).ajaxStop($.unblockUI);
$("nav.setup-nav a").not("[target='_blank']").on("click", function (event){
event.preventDefault();
var href=$(this).attr('href');
$.ajax({
type:"POST",
url:href,
success:function (data){
$(".contentPanel").html(data);
$(this).blur();
$("html, body").animate({ scrollTop:100, scrollLeft:400}, 600);
},
});
return false;
});
});
Which forces all the content of the linked-to pages in the nav menu to load inside a div in the center of the page. That is, except for pages with target="_blank" attribute. This is so event.preventDefault and the UI blocking stuff doesn't get called when linking to an external page that we want to load in a new window. I'll try to concisely describe my issue: One of the menu items is (conditionally) a link to a web-based MPD client, which we definitely do NOT want to load inside a div on the same page, and thus has target="_blank" attribute. The problem is the user can also choose to enable or disable the MPD daemon through the web-interface. PHP handles the setting of all these kinds of state variables. Basically like this:
if ($config->is_flag_set($MPD_FLAG))
{
echo '<li><a target="_blank" id="mpd" href="rompr/">Local Playback Web Interface</a></li>';
}
else
{
echo '<li><a id="mpd" href="local-disabled.php">Local Playback Web Interface</a></li>';
}
and so when the page first loads, if the MPD daemon is not running the link to the web interface is pointed to a page that explains MPD is not enabled. This link does NOT contain the target="_blank" attribute. However, if one navigates to the settings form and switches on MPD, there is logic to replace the href and target attributes of that particular link, so theoretically all should work as if the page had loaded initially with the MPD flag on (if that is clear!). The problem is that when the "replaced" link with target="_blank" (set by .prop() or .attr(), I've tried both and it doesn't seem to make a difference) is clicked, the page still loads inside the div!I tried duplicating the click handler that's defined within $().ready and putting it in another function which I call after the link attributes are set, but it still doesn't work as I imagine it should! Just to verify that I wasn't crazy, I used .each() to print all the links that did and did not have the target="_blank" attribute and that all corresponds to what I believe it should be. Why is the replaced link not getting treated as if it has a target="_blank" attribute in the click handler? By the way, Going the other way and removing the target="_blank" attribute if MPD is turned off, works like a charm. Thanks so much in advance for any answers, and my apologies if I have duplicated a previous question!
Cheers,
Events are always tricky anytime you have to reload elements with ajax. The best way I've found is to attach the event to some container element that will not reload:
$('#always_present_container').on('click', "nav.setup-nav a", function (event){
if($(this).attr('target') != '_blank'){
...
}
});
that way the element is checked for the attribute when its container is clicked. When you set up $('element').click() the selector is checked on the page load and the events attached then, so when you reload something via ajax the new element doesn't get this event attached.
Note: normally you could avoid the conditional statement in the function, but I didn't know of an easy way to filter by target in a css selector.

Targeting links with jquery mobile

This is pretty much an add on to a question I posted before about loading an external page without ajax, but keeping it an iOS web app window. What I came up with for that example was this
<script>
$(document).bind('pageinit', function() {
$("#test").click(function (event) {
event.preventDefault();
window.location.assign("test.html");
});
});
</script>
But now what I want to do is to set this up for every link I would have on that page. Seeing as I don't know how many links I could have, it would be very tedious to do this every time I add a new link. So I found this snippet and thought I could combined the two some how, I just need some direction on how.
$('a').each(function(index){
var elementId=$(this). attr("id");
elementId='#'=elementId;
So for each a tag or href on my page, it will automatically grab the link and load it in that particular manner automatically.
Of course you can combine your codes. Anyway I haven't tried your code but you have to wrap an .each() function around your click events. Also you should give every clickable link a the same class. Should look like this:
$('.class').each(function(){
$(this).click(function(){
event.preventDefault();
window.location.assign("test.html");
})
});
if you now want those links to link on different pages you can define a data-href attribute on each link. like this: data-href="test2.html" in your html.
You can now use
$(this).data("href");
and put the output into a variable. Afterwards you can place it in your window.location.assign thing dynamically.
Hope I understood your problem and it helped.

how to load a different html page without refreshing the page or changing the url?

I want to load an html page without refreshing the page or changing its url.
So for example, If I am at http://localhost/sample/home and I want to navigate to contact us page, I click on the contact link and the contact page content gets loaded without refreshing the page or changing the url.
How this can be done?
Look into the use of jQuery.load().
This allows you to load HTML from a URL, and display it in an element in your page.
Therefore you could do something like:
$("body").load("/sample/contactus");
However I wouldn't recommend this as its not great for SEO or accessibility. Also it wouldn't reduce load time because you still need to make a HTTP Request for a whole other page..
Mock HTML:
<div id="links">
Contact Us
</div>
<div id="content"></div>
JS:
$(function() {
$("#links > a").click(function(e) {
e.preventDefault(); //so the browser doesn't follow the link
$("#content").load(this.href, function() {
//execute here after load completed
});
});
});
jQuery .load() - Load data from the server and place the returned HTML into the matched element
Something like :
$('#content').load('ajax/contact.html', function() {
alert('Load was performed.');
});
http://api.jquery.com/load/

jQuery Mobile load second page from new html

Say I wanna load a new html file, with some jQuery pages, like this:
$.mobile.changePage("some_page.html");
If this html file has two pages inside, how do I load not the first, but the second page?
I Tried
$.mobile.changePage("some_page.html#second_page_id");
But it doesn't work.
Thanks
Dude try to make your second page element data-url as <div data-url="page.html&subpageidentifier">
in the target html page. and let me know is that really worked for you.
The $.mobile.changePage() function takes the first div with data-role="page" and loads it into the dom with an AJAX call. The best solution is to move the second page to the top of the html code.
Otherwise, if you want to decide to load the first or second page, you could put them in different files.
Maybe there's a way of calling the second page, but i have no idea of how to accomplish this.
You can manually grab the element you want:
//delegate the event binding for some link(s)
$(document).delegate('a.my-link', 'click', function () {
//show the loading spinner
$.mobile.showPageLoadingMsg();
//make the AJAX request for the link's href attribute
$.ajax({
url : this.href,
success : function (serverResponse) {
//get the data-role="page" elements out of the server response
var $elements = $(serverResponse).find('[data-role="page"]');
//you can now access each `data-role="page` element in the `$elements` object
$elements.filter('#page-id').appendTo('body');
//now use changePage to navigate to the newly added page
$.mobile.changePage($('#page-id'), { /*options*/ });
//hide the loading spinner
$.mobile.hidePageLoadingMsg();
},
error : function (jqXHR, textStatus, errorThrown) { /*Don't forget to handler errors*/ }
});
//stop the default behavior of the link, also stop the event from bubbling
return false;
});
But I have to say, with the way jQuery Mobile currently works, you're better off putting each data-role="page" elements in a separate document.
ทำแบบนี้ครับ
ออก
สำคัญคือให้ใส่ data-ajax="false"
คุณก็จะ changepage ได้จากต่างหน้า

jQuery replace all HTML

I'm trying to replace all the HTML (including the HTML tags) with another page. What I'm trying to do is having a website acting as an app even when navigating the another page.
Here is the code :
(function($) {
Drupal.behaviors.loadingPage = {
attach: function(context,settings) {
$('a').click(function(event) {
event.preventDefault();
// Create the loading icon
// ...
$.ajax({
url: $(this).attr('href'),
success: function(data) {
$('html').replaceWith(data);
}
});
});
}
};
})(jQuery);
I've tried several things. replaceWith() causes a jQuery error in jquery.js after deleting the HTML tag, I guess it is because it can't find the parent anymore to add the replacement.
The best result I got was with document.write(data). The problem is, the javascript code on the loaded page is not executed.
Anyone got a better idea ?
A better idea? Yeah, just load the new page normally by setting window.location instead of using AJAX. Or submit a form.
Otherwise, if you want to load something to replace all of the visible content of the current page but keep the current page's script going, put all the visible content in a frame sized to fill the browser window - which, again, you wouldn't populate using AJAX.
(I like AJAX, but I don't see why you'd use it to replace a whole page.)

Categories