Reloading a Page (or part of a page) using JavaScript - javascript

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 ;-)

Related

JQuery Ajax not replacing div element with text file

So, I'm quite new to JQuery, and AJAX in general. I've made an app to retrieve data from Spotify's API, which writes to song.txt (This part works just fine. It updates every second, as it should.) and the HTML file will pull the contents of song.txt and change the div with id of 'track'
<!DOCTYPE html>
<html>
<head>
<title>Camashima's Site</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function () {
$(document).ready(function () {
$('#track').load('../output/song.txt');
});
});
</script>
</head>
<body>
Currently Playing:
<div id="track">
.
</div>
</body>
</html>
The JS code posts the html file to the server just fine, and I see Currently playing: but nothing else. So that tells me it's not the issue. So, what am I doing wrong here? It should be loading song.txt into the "track" div, right?
Also, I'm using Goorm-ide to host my container, and the console isn't as in-depth as chrome's dev tools.
Expected: "track" div to be replaced with song.txt contents
Result: Nothing happens.
Whether or not the AJAX part works, the main problem here is that you're (1) adding tons of document.ready events and (2) doing so indefinitely in very rapid succession.
You can correct this by (1) using one document.ready event and setting your interval within that and (2) providing a delay to the interval, even if it's just one second. For example:
$(document).ready(function () {
// execute this code once, and only once, when the document is ready
setInterval(function () {
$('#track').load('../output/song.txt');
}, 1000); // perform this interval operation every 1000 ms
});
From there, you can then begin to reasonably debug the AJAX issue (if there even is one). I realize in a comment on the question you indicated that Chrome developer tools are disabled. So you'll either need to correct that or find another tool to use to debug it. But you're essentially going to want to observe the AJAX requests and responses. Confirm that the address being requested is what you expect it to be, and observe the response from the server. The client-side code here is extremely simple and "works" just fine, but if the overall result isn't what's expected then your only recourse is to debug those interactions with the server.

My script is causing infinite loop

To begin with: I'm a total newb. These functions are the first I have ever written. I use Wordpress (and the most important plugin used on the site is called BuddyPress). What I essentially want the script to make is delete something from my database and then reload the page one time when pressing a certain link. Nothing more.
I have an issue with Internet Explorer where my page gets stuck in an infinite loop. This problem doesn't occur on Chrome at all. I have a PHP containing the following:
<li><a id="edit" href="#" onclick="runUpdateForm();">Uppdatera profil</a></li>
When pressing the link the following script is run:
<!--Javascript runUpdateForm-->
<script type="text/javascript">
function runUpdateForm() {
$.post ( ajaxurl, {
action:'resetUser',
user_id:jQuery("#user_id").val()
});
window.location.reload();
}
</script>
<!--End Javascript runUpdateForm-->
In my functions-file the following is found:
function resetUser() {
$user_id=get_current_user_id();
global $wpdb;
$wpdb->query("DELETE FROM wp_profile_updates WHERE user_id='".$user_id."'");
die(); // close the connection
}
add_action('wp_ajax_resetUser', 'resetUser'); // add action for logged users
add_action( 'wp_ajax_nopriv_resetUser', 'resetUser' ); // add action for unlogged users
After Googling a bit I found the following piece of code which I put right above location.reload():
history.pushState("", document.title, window.location.pathname + window.location.search);
This made the infinite-loop go away but still it reloads one time to much in Internet Explorer, in comparision to Chrome and what I actually want to happen.
Sorry for my poor English. I'm a Swede :-)
I appreciate the help. I need someone with knowledge to tell me if they see anything right away which looks crazy and should be changed. My problem maybe is related to other stuff happening on my site.
Regards.
Your code does: start the ajax, then reload. as ajax is async, it will never post to the server, its interrupted by the reload. So you need to await the ajax:
<script type="text/javascript">
function runUpdateForm() {
$.post ( ajaxurl, {
action:'resetUser',
user_id:jQuery("#user_id").val()
},function(){
// executed on success
window.location.reload();
});
}
</script>
also, im wondering where ajaxurl is defined...

redirect to other html file with parameters

I want to redirect from a.html to b.html with a parameter for example array c[],i used something like location.href = "b.html"; but when i write something like console.log(c[0].name); in my .js i got nothing after the redirection to b.html!
thanks in advance for your help :)
$(".btn").click(function(){
location.href = "b.html";
//.. push of some elemts to the array elements
// .. try to show elements in b.html with console.log() for example
});
As commented before, once you are redirected, you are literally on a new page. So everything you had before is unloaded. ( And your script which is supposed to execute after setting the location.href is stopped )
There are several ways to handle data into the next page, but by far the most easiest one would be to use query-parameter in your URI. Check that out:
https://en.wikipedia.org/wiki/Query_string
You are limited by the size of data, the data is somehow visible, and it could be easily hacked, though - but it seems you are quite at the start of something anyway.(?)

js/jquery Async Content Overwrites Page

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');

JavaScript load faster?

<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

Categories

Resources