<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var siteTitle = $.ajax({
url: 'http/',
type: 'POST',
data: { http: 'siteTitle' },
success: function(title) {
$('.title').html(title);
}
});
</script>
I have a site title and it's grabbed through jQuery's $.ajax() call. The title of the site needs to be configurable. So I grab the title through the ajax request but it doesn't show up on the site for about ~1.5s.
Is there anyway to decrease this time?
The site title is in about 6 places so it looks awkward with nothing there for ~1.5s.
Thanks.
I would recommend that you handle the configurable title on the server and render it with the page instead of requesting it through ajax.
Not sure what server side language you're using, but most will have a way to generate dynamic content on the server and pass it back to the browser.
Have some default text like "loading..." as your title value. Then it won't be so bad when the ajax call updates it 1-2 seconds later.
If it is a span element (instead of a window title) then maybe even a loading gif. I think users are getting used to seeing those spinners now and won't question the extra 1-2 seconds wait time for the actual title
Related
ive ran into the following Problem and maybe someone can give me a little advice or a way around this. I have the following Problem:
A Partner of my Page provided me with a Code that i should use on my Page, which writes some Content to my Page that i really want.
Unfortunately this Content is only relevant to People living in a certain region.
So i am using the service of an ip-api which returns the region the current user is in and lets me work with that. This is done with a jsonp ajax call.
If the Person is in the right Region the Code should be executed, if he is not, it shouldnt.
The Problem is that the code to be executed contains a document.write. So if i call that code inside of the ip-api callback the document is allready loaded and the document.write will overwrite my page.
So the big Question is: Is there a way to capture the document.write output into a variable like with PHPs output buffer? Or maybe some way to overwrite the content of an iframe instead of the whole Page? Anything that prevents the document.write from overwriting the page and redirects its output into a part of my page would be sufficient.
Thanks for your time :)
PS: this is the code im talking about:
$.ajax({
url: "http://ip-api.com/json/",
dataType: "jsonp",
success: function( response ) {
if(
response["city"]=="Hamburg" ||
response["region"]=="SH" ||
response["region"]=="NW"
){
document.write("Some Content here");
}
}
});
Replace
document.write("Some Content here");
with
$('#my-container').html('Some content here');
I am searching this for an hour but I dont get any perfect solution for it. I want pagination which doesnot load all data at once and loads only what are currently showing on the page. I dont want to refresh whole page while going from 1st page to any other page of pagination. And I am preffering to use JQuery. Just give me any good pagination link. I dont have tables I have divisions for pagination
This would be pretty simple to do by hand, no libraries needed. You'd put an event listener on the buttons
$('#button').on('click', function(){
changePage($(this).data('page-number');
}
var changePage = function(pageNumber)
{
$.ajax({
url: 'whatever.php',
data: {
page_number: pageNumber
},
success: function(r){
var html = //build html based on ajax respone
$('#page-wrapper').empty().append(html);
}
});
}
Realistically though if there are not going to be a huge amount of pages, you should get the data for ALL the pages and simply store it in Javascript variables and then access those variables when you click a page number.
I have a small digital signage web application where all the pages shown is created in HTML and stored in a database.
I need to make some sort of player that will display all my slides. I have a URL to call that gives me the next page to show: http://example.com/PlayNext This will return the next slide in the given context.
Right now i just have a timeout that will reload the page every 10 seconds. I want to make a much more smooth experience with the player, and load everything from client, without postbacks to server.
So what im thinking is to load the next page in an off screen tag and when thats loaded, slid it into view, and then start loading the next slide off screen. When the show duration has passed, then slide the next page into view and start loading the next one, etc.....
What im wondering is how actually to do this off screen loading thing. I know i can set overflow to be hidden and just place it 3000 px off screen. But how do i make the continuous flow that will allow me to show all the pages i want ?
And a side note - how do i clean up the divs when they no longer should be in use? so that my browser isnt leaking memory?
edit
This is the current "player", it is ASP.NET Razor syntax to show the next page url etc. this is what i want changed to load it in an off screen div:
<script type="text/javascript">
var duration = #ViewBag.Duration;
var nextPage = "#ViewBag.Address";
window.setTimeout(reloadbrowser, duration);
function reloadbrowser()
{
var path = $.ajax({
url: "/page/Ping",
success: success,
error: reloadbrowser,
timeout:5000
});
}
function success()
{
window.location.href = nextPage;
}
</script>
</head>
<body style="height:100%">#Html.Raw(ViewBag.BodyXHTML)</body>
</html>
if the url http://example.com/PlayNext is a url which retrieves the html from the database then these are the steps you should take:
1. you need to get the html from the database using ajax()
2. load that html inside an iframe
3. position that iframe outside of viewport (position:absolute; left:-100%;)
4. after the iframe is loaded, slide it inside the viewport and the old one outside and then remove() the old one
so you'd come up with something like this:
$(function(){
function getData(){
clearTimeout(window.theInterval);
$.ajax({
url: "http://example.com/PlayNext",
type: "POST",
timeout:5000,
success : function (databack) {
var iframe=$('<iframe>'+databack+'<iframe/>', {
style:'position:absolute; left:-100%;',
load:function(){
var that=this;
$(this).animate({
left:0
},500);
$('iframe').not(this).animate({
left:'-100%'
},500,function(){
$('iframe').not(that).remove();
});
}
});
$('body').append(iframe);
window.theInterval=setTimeout(function(){
getData();
},10000);
},
error:function(jqXHR, status, message){
getData();
}
});
}
getData();
});
NOTE: you must build on this answer to match your project
why use an iframe and not a div
I'm gonna quote some benefits of using an iframe for loading websites inside another one from this answer
1) Iframes implement the cross domain origin policy (images, scripts, and styles do not). This can be useful for pulling in sites / content from other domain names relatively safely. Basically, this allows the advantage of being able to visually show data from other domains without letting them stomp all over your page with unlimited access (like something like JSONP would be able to do).
and the next thing is:
2) You can send multiple types of resources from within an iframe, not just certain mime-types (you're relatively limited to application/javascript, application/x-javascript, text/css, text/xml, image/png, image/jpeg, image/gif with scripts, XHR, images, and sources). For instance, if I want to show you a PDF, I can open an iframe and let the Adobe Reader plugin show you that file. Additionally, in the same domain, if I want to pipeline a script, style, and image all together (inline on the page, image would have to be data URI), I can accomplish this with an iframe (and if it's in the same domain, port, and protocol I can access it with JavaScript as well).
The client I am working for is trying to make it so that his page never has to reload. Instead he just wants to use AJAX. Now I realize that the way im doing it is not a very efficient way to do it but it is the easiest and you would understand why if you would see his site..
I'm trying to get it to work so that AJAX will refresh only parts of the page or the whole page.
My code is:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
function refresh (update) {
$.get(location.href, function (data) {
console.log(data);
var EL = $(data).find(update);
var HTML = $('<div>').append(EL.clone()).html()
alert(HTML);
$(update).replaceWith(HTML);
});
}
</script>
</head>
<body>
<div style="font-size: 64px;">The current timestamp is <b class="time"><?php echo rand(999, 9999999); ?></b></div>
<br><br>
<button onclick="refresh('.time')">Refresh Time</button>
</body>
</html>
When you first load the page PHP generates a random number. Hitting the refresh button is suppose to refresh this number. However, the same number stays there. The request returns the exact same page instead of return a page with a new number.
And again, people note that I know this is not a very efficient way to do this, but its the way i'm trying to get it to work
Am I doing something wrong? (besides requesting the whole page when only actually using part)
EDIT
You can try it out here: http://methods.x10.mx/projects/refreshPageParts.php
Change your call to this, to break the caching:
function refresh (update) {
$.ajax({
type: "get",
cache: false,
url: location.href,
success: function (data) {
$(update).replaceWith($(data).find(update));
}
});
}
See the notes on caching in the documentation: http://api.jquery.com/jQuery.ajax/
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.
I tested your example on my local wamp stack and it is working fine!
btw: you forgot semicolon after the following line (It is not necessary though)
var HTML = $('<div>').append(EL.clone()).html();
EDIT: your code is working... also on the url you provided. The strange thing is you have to wait a few minutes before it is working. So when you visit the page and press the button, the time won't be updated... however if you wait few minutes it will... only once then you have to wait again. I bet your server is caching the page. So your problem is server side... disable the cache and it will work!!
EDIT:
you also could try to make the get url dynamic with a dummy parameter like so
http://methods.x10.mx/projects/refreshPageParts.php?v=dummy
maybe you don't have to make dummy dynamic, it might work with a static variable also. i'm curious, let me know ;-)
I am new to Jquery mobile.
I am trying to get Sliding effect when i navigate to another page say # display2 from thie below code.
but i am not able to get slide effect.
If I remove the rel="external" i am able to slide but on the #display2(page whihc i would navigate to),the query string values are returned as null.
so if i put rel="external" the parameters are passed to #display2 but slide transition not working.
if i remove re="external" slide works but the querystring parameters are returned null.
can you please let me know is there a way where both of them work together.
('#display').on('pagebeforeshow', function () {
// $(this).find('[data-role=header] .ui-title').text(json.getLOBXMLResult[currentItem].FolderName);
$.ajax("AppstoreWS.svc/getLOBXML", {
beforeSend: function (xhr) {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
contentType: 'application/json',
dataType: 'json',
type: 'GET',
error: function () {
//alert('Something awful happened');
},
success: function (data) {
result1 = data.getLOBXMLResult;
$('#categoryList').children().remove('li');
$.each(result1, function (index, output) {
$('#categoryList').append('<li>' + output.FolderName + '</li>');
});
$('#categoryList').listview('refresh');
}
});
});
Part 1 - why rel=external worked & other options
The reason why rel=external works with no transition is because this expects the browser to open an external page and therefore, disable ajax. To counter-effect this, you've got numerous options :
By using Single page template
You could make your two pages into a single page. This is called a single page template and your second page's reference would be #page2 (or any name you'd give as the ID). This is how it'd look like :
<div data-role="page" id="page1">
<!--Stuff in page 1-->
</div>
<div data-role="page" id="page2">
<!--page 2 stuff-->
</div>
Advantages
The DOM can leverage the power of ajax driven navigation.
This would make partial loading, script loading easy, as you'll need to refer all this only once.
Data-transfer between pages is very simple. You'll just have to store the data in you need in a global variable or in the data property of the #page2, and retrieve it in the pageinit or pageshow (or any event) of the second page.
Transitions, etc will work.
There will be no page refresh.
Disadvantages
If the HTML content of the two pages are large, it'll be difficult for maintenance.
By using rel=external
As you might have seen, rel=external can be used only when a page refresh is absolutely needed. Its upto the user's choice. If an a tag is marked with rel=external it means the browser will treat it as an external link, and will ignore jQuery Mobile's ajax navigation system.
By referring all the scripts of page 2 in page 1
Generally, to be able to use page transitions, you must use ajax system of navigation in jQM. So the general behaviour of ajax is as follows :
page1 will request for page2 in page2.html.
The <body> of page2.html alone is taken from page2.html.
The <head> section( which might contain your scripts, which might have your query-string logic) will be ignored.
So to change this, you can refer to page2's scripts in page1.html's head so that these scripts will be loaded and ready when jQM's ajax system pulls the body of page2.html.
<script src="jqm.js"></script>
<script src="page1.js"></script>
<!--page 2 scripts-->
<script src="page2.js"></script>
Advantages
Your transitions will be working properly.
The common scripts will not be referred to multiple times, hence much faster loading times.
Query strings will also work
Disadvantages
If the two pages have very little in common, you'll end up having unwanted scripts in your first page.
What if you have more than two pages? What if you have 10 pages? Will you refer to all 10 pages' scripts in page1. I dont think thats the way.
By referring to page2 scripts inside "data-role=page" section of page2.html (recommended)
This will bring the scripts along with the page when ajax brings it in. This will also work with query strings. This will look something like this :
<div data-role="page" id="page2">
<script src="page2.js"></script>
<!--- your html-->
</div>
Advantages
The scripts pertaining to a particular page are restricted to within that page.
Transitions will work.
Query strings will also work
Part 2 - alternative to query string
The reason I'm saying this because Query strings are archaic technology, because at that time, there was no way to store to data. They're also insecure because user can see the data you send over the URL. You must consider using something like localStorage. I'm not saying you must NOT use query strings. It's just that there are better options available for mobile data storage. See this link for more info about how you can use this localStorage. Also, see this for all the options you have. Now, looking at your query string :
platform=' + output.FolderName + '&sid=test
This could easily be made into an object. So in the click function of the anchor tag inside <li>,
$(document).on("click", "li a", function(e) {
//stop default action.
e.preventDefault();
//take the href; Im assuming its page2.html?platform=outputFolder&sid=test
var params = this.href.split("?");
//now params[0] = page2.html
//param[1] = platform=outputFolder&sid=test
//set this in localStorage
localStorage["page2params"] = param[1];
//change to page2.html
$.mobile.changePage("page2.html", { transition : slide });
})
Then, in the page2.html's pageinit method, you could retrieve it for your use :
//assuming you have a page with page2 as id in page2.html
$(document).on("pageinit", "#page2", function() {
var params = localStorage["page2params"];
//do anything you want with params.
});