JQuery Ajax not replacing div element with text file - javascript

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.

Related

why the data not loaded in the table when the page in the print dialog

i have a problem here
i make a page that have function for print page that contain of dynamic table. the print function method is open the page html that contain the dynamic table in the new tab then open the print dialog. the process going well but when i add the ajax call for displaying the data in the dynamic table. the data not displayed at the table in the print dialog..but when i cancel the print dialog and the page that must be printed show off the data is displaying there...
how to fix it.
this the picture of the page
i use this code for print that
<script>
function myFunction() {
window.open('SPL.html','','height=650,width=1200').print();
}
</script>
You didnt provided yet the code of your generator, so I simply explain you why its not working and what you can do.
A good reference for window Mozilla Window Open
You can read there more details about possible functions and more. Your problem is, with:
window.open('SPL.html','','height=650,width=1200').print();
Directly after opening the file you call the print function, at this moment your script and ajax request don´t have finished yet. Thats why it just shows you the current state with the predefined html and css code.
So what you have to do is simply call print after it has finished. There are tons of ways to achieve this.
The simplest way would it to open it like this:
window.open('SPL.html','','height=650,width=1200')
Inside your SPL.html you stack your js script inside:
$(document).ready() {
//Your Generator
}
This little piece keeps safe that all dependencys (external scripts and dom elements) are created before your generator runs and it gives us the possibility for the next function:
$(window).load(function(){
window.print()
});
This one is a version of the globalEventHandler window.onload. It basicly ,if you read the documentation, fires after everything is loaded, including images, frames, objects and so on. And the tricky part also after document.ready, this makes it sure that our generator is finished before we run the print command.
I hope this helps, If you really want to stick the print command inside your first page I can give you an example of this too. But it is not as bullet prove as this solution. Ah and if you want to stick with #Saurabh solution you have to use allow-modals for your Iframe, if not it wouldn´t be possible to print. Is also mentioned in the official documentation.
This issue is caused because the page is not completely loaded before calling the print function.
Update: Using jQuery
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function(){
$('#loaderFrame').load(function(){
var w = (this.contentWindow || this.contentDocument.defaultView);
w.print();
});
$('#loaderFrame').attr('src', 'SPL.html');
});
});
</script>
<style>
#loaderFrame{
visibility: hidden;
height: 1px;
width: 1px;
}
</style>
</head>
<body>
<iframe id="loaderFrame" ></iframe>
</body>
</html>

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

ERROR: 508 (Loop detected)

Well, this isn't like a proper question or anything..
I am just a bit curious, tried searching but couldn't find accurate answer for my problem so I had decided to try out and ask another question out here.
I have this small fun-time project in which you are supposed to keep on clicking a button until you gain the highest clicks among the other players, I have a page ManageClick.php which has the following code in it -
<?
sleep(rand(1,3));
$storage = fopen("TOTAL.txt", "r+");
if (flock($storage, LOCK_EX)) {
$a = fread($storage,filesize("TOTAL.txt"));
$a++;
fseek($storage, 0);
fwrite($storage, $a);
flock($storage, LOCK_UN);
} else {
}
fclose($storage);
?>
The above adds a random delay between 1-3 seconds and then opens a file TOTAL.txt reads it, and adds +1 to the value in the file.
I have a main page Testpage.html which has a simple button and a JQuery function which calls the page ManageClick.php when the button is clicked. However, now the problem arises. Whenever an user rapidly clicks the button in the main page it shows the following error in the Console window-
GET http://domain.tk/ManageClick.php 508 (Loop Detected)
GET http://domain.tk/TOTAL.txt 508 (Loop Detected)
WHERE domain is my website's name.
Any idea what could be causing the following issue? Rapid clicking of the button is one of them which I guess sends multiple requests to the page and causes the 508 error. Also, any possible way in which I could try and fix this error from showing up in the Console?
Also, please note that I am not English... Sorry for it.
PLEASE SEE- Adding the code of my Testpage.html for better quality of help.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function(){
$("img").click(function() {
var test = $("#Clicks").load("TOTAL.txt");
$.post('ManageClick.php');
});
});
</script>
</head>
<body >
<center>
<img src='ABCD.png'>
<div id='Clicks' style=""></div>
</body>
</html>
If I understood, you have a webpage that has a game in which you call a php script to save how many times the user has clicked on a button.
You say the console (I guess chrome's developper tools or the similar) returns a 508 error as "Loop detected". This is the server telling the client that there might be a loop in the code because it gets called too many times. Well... it's not an automated redirect, it's just you calling it tons of times.
According to your explanation of the game, I would rather save the number of clicks in a javascript variable, and send them only after the game ended. This way, you only call the server one time.
On the other hand, your php code assumes that there's only one user of your website. I mean, you save the value in a file, but it doesn't take in account who's game is it.
Think that if you and I opened the website at the same time, you start adding clicks, and then I add another one, but the count gets saved in the same place.
Edit: Code example
jQuery:
var test = $("#Clicks").load("TOTAL.txt");
$("img").click(function() {
test = parseInt(test) + 1;
});
With this, you load the number previously stored and keep count of the clicks. Next you need to build a function that sends the click count after some idle time (or if you have a timeout per round )
I'll assume that if the user spent 3 seconds without clicking, he's gone, so I update the server. The new jquery would be:
var test = $("#Clicks").load("TOTAL.txt");
var wdt;
$("img").click(function() {
wdt = setTimeout(serversync, 3000);
test = parseInt(test) + 1;
});
function serversync(){
$.post('ManageClick.php?count='+test);
}
In this code I added the serversync function. It runs after 3000 ms have gone for the setTimeout(). This timeout gets fired when the user clicks, but if there's a click again, the timer resets.
Finally, you should pass the new count value to the ManageClick.php script. I passed it as the count GET attribute (which you can retrieve in your php by $_GET['count']
Of course, this is not perfect nor safe (I could easily fake a massive count to be sent to the server, but that's another story), but it's the idea
Your webserver is detecting a long running script based on some configuration. I'd bet if you take out the sleep function, it would no longer detect a loop.
Also, if you are expecting the value in TOTAL.txt to increase, be sure to cast as integer.
$a = fread($storage,filesize("TOTAL.txt"));
$a = (integer) $a; // cast as integer
$a++; // now you can increase it
To further mitigate this issue, if you must keep the lseep() function, use the following steps in your html/js:
click_button (call ajax)
disable_button (while ajax is running/php is sleeping)
accept_ajax_return_value (when ajax responds)
re-enable button (after ajax is complete and can go again)

Change html before rendering to avoid a flicker

I have code I'd like to run before the page is rendered. For example updating dates from absolute time to relative time or converting raw text (or markdown) to html. If I reload the page several times I can see occasionally there's flickering updating the changes. How do I run the code as it's drawn instead at the end where it needs to redraw everything?
I tried document.addEventListener('beforeload' it appears that event is depreciated and no longer supported in chrome
You'll need to think about your page lifecycle.
When your page is being loaded, if a <script> tag is encountered, it will immediately be executed, and prevent any more content being rendered until that script is complete. This isn't recommended practice.
But, to answer your question, you could do something like this:
<p>Your next reward will be available in <span id="nextRewardTime">3600</span>.</p>
<script type="text/javascript">
var $el = $('#nextRewardTime');
$el.text(format($el.text());
</script>
<p>Come back soon!</p>
Now, immediately after the first <p> is downloaded by the browser, it'll hit the <script> tag and execute the JS. Only once that is complete will it download the next <p> tag ('Come back soon!').
You can't attach an event handler to the Javascript before it's been rendered on the DOM, because... well... it's not on the DOM.
The better way of doing this is to format the thing correctly on the server in the first place.
Edit: Also, scattering script tags throughout your page makes your code really unmaintainable!
I would use document.readyState and a self-invoking function:
<body>
<script>
function executeFunction() {
//do stuff - such as check for anchor tags
$("a").html('Replaced');
if (document.readyState === 'loading') executeFunction(); // repeat to ensure all the tags get innerHTML-ed
}
(function(){
if (document.readyState === 'loading') executeFunction();
})();
</script>
<!-- more HTML -->
</body>
It seems that you want JS to execute as the page is loading. You may also want to try using uninitialized as the ready state (which occurs before "loading").

Reloading a Page (or part of a page) using 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 ;-)

Categories

Resources