This has been well answered several times, but being new to js I must be missing something basic.
My simple chat page works well, but refreshes only on manual call, and I want it to auto-refresh.
The php fetches the comment via POST, writes it to the log file (in the same directory), then writes the updated log file to the div.
<div id="show"><?php include 'LOG.txt' ; ?></div>
I adapted the following code from another post and tried it in header and in body, but it is not working.
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
setInterval(function(){doRefresh()}, 5000);
</script>
What does this need?
Thank you.
Your code is mostly correct. However, you want to make sure that you only fire the function only at DOM ready, if your code is in the header. And of course you have to include jQuery.
NOTE: If you place your code just before </body> as it is, it should work.
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
$(function() {
setInterval(doRefresh, 5000);
});
</script>
setInterval() method will continue be calling until clearInterval() method is called, or when window is closed.
setTimeout() method calls a function after a specified number of milliseconds.
I'm used to treat such cases as the example below :
function doRefresh()
{
$("#show").load("LOG.txt");
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
By calling function itself like this example, with the setTimeout() method, it will be called every 2 seconds.
See my jsfiddle version
try Via Ajax
function doRefresh(){
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
Check console for Error.
https://stackoverflow.com/a/6470614/6079755
Related
I want a SVG file to be loaded in a variable before $(window).load() will be fired.
I load the file using jQuery.get(). The problem is, that this function works asynchronously and by the time, when the SVG file is read, the $(window).load() is already invoked.
So I have following code:
var data;
$(document).ready(function () {
jQuery.get(
"my.svg",
function (_data) {
data = _data;
},
'text');
});
$(window).load( function () {
alert(data);
});
The alert will show "undefined". If it will be invoked later (after 5 seconds for example) then it will show the content of the SVG file.
Any suggestions? Thanks!
I agree that setInterval would probably be the solution you want IF you want to do stuff the hard way because you can never tell how long an AJAX request is going to take.
I would recommend restructuring your code to be more like this:
<script>
$(document).ready(function () {
//this can remain async: TRUE
jQuery.get(
"my.svg",
function (_data) {
//call function to do something to svg file
//if you are relying on the SVG to be there in order to call an action
//then why not wait for the SVG to load first and then call the action
svgAction(_data);
},
'text');
function svgAction(img_code){
//do something with img code now
}
});
</script>
I have a problem with triggering a function which needs to be loaded only one time.But I don't want to put it into:
jQuery(document).ready(function ($) {
});
I want to run it separate.
I have tried:
jQuery(document).one(function () {
myfunction();
});
and some other stuff.
But couldn't solve it.
UPDATE:
I have my webservice on ready():
jQuery(document).ready(function ($) {
PageMethods.myWebSer(suc, fail);
});
function suc(){
//I want to run my function here , but only one time
//Examplle
//jQuery(document).one(function () {
// myfunction();
// });
}
Thank You
Just add another ready or load function : you may have as many as you want, they will all be called in order :
jQuery(document).ready(function() {
// this will be run
});
jQuery(document).ready(function() {
// and this one too (after the other one)
});
It you want it to run onload use:
jQuery(window).load(function () {
// run
});
Keep in mind that ready fires before load.
$.when() .then() is not working for me, what am I doing wrong? Thanks in advance for your help. I want to make sure the form is loaded first then I want to populate a <div> inside the form to show Google's recaptcha. This is the test: It actually loads the form but the alerts are not poping up at all. I the test works I'll change the "alerts" to call the showRecaptcha function.
<script type="text/javascript">
$("document").ready(function () {
function showRecaptcha(element) {
Recaptcha.create("publick_key_here", element, {
theme: "red",
callback: Recaptcha.focus_response_field});
};
// load the form
$.get('../php/formularioDeReserva.html', function (data) {
$.when($('.subscriptionForm').html(data))
.then(function(){alert('Then')})
.fail(function(){alert( 'failed.' )});
alert('I reached this point.');
});
})
</script>
Note for Felix: My tests show that .html(data) is not done instantaneously. In the following code if I leave the alert('Load was performed.') the pause of the alert give some time so the showRecaptcha succeds. If I remove the alert nothing works.
$.get('../php/formularioDeReserva.html', function (data) {
$('.subscriptionForm').html(data);
alert('Load was performed.');
showRecaptcha('recaptcha_div');
});
Note for Guiherme: Trying what you suggested, which seems to me a good logical idea, still does not work, and I don't understand why not. In the following code the subcritionForm shows but the success, error and complete alerts do not pop up at all.
$.get('../php/formularioDeReserva.html', function (data) {
$('.subscriptionForm').html(data);
// alert('Load was performed.');
// showRecaptcha('recaptcha_div');
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
Note: When did a "view source" I realized that the Java script was included twice because one of the file was not saving properly. That explained why the alerts were popping twice.
You need to call the
$.when()
before the
$.get()
but, if it just one get request, why don't use
$.ajax({...}).success(function(data){..}).error(function(){...})...;
or
$.get({...})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
even that, I think the fail() will never be call in that case.
I gave up !!!
I decided to rename the main .html file to .php and use an php include statement instead of the .get:
<div class="subscriptionForm">
<?php include("../php/formularioDeReserva.html"); ?>
</div>
and changed the jQuery to a simple calling to show recaptcha:
$("document").ready(function () {
function showRecaptcha(element) {
Recaptcha.create("public key here", element, {
theme: "red",
callback: Recaptcha.focus_response_field});
};
showRecaptcha('recaptcha_div');
[..more here..]
});
Thanks all for your help.
Update: I have just realized that perhaps I needed to create a deferral and create a promise, but I don't really understand the concept and at the end it was easy just to use an php include.
$(document).ready(handler) executes once the DOM is fully loaded. If content is later added to the page using AJAX, which contains a $(document).ready(handler) function, this function is executed immediately, per the jQuery API. Additionally, .ready can only be called on a jQuery object matching the current document.
This is not what I want, however :)
How can I achieve this .ready type of functionality for data loaded via AJAX after .ready has already fired, in a cross-browser compliant manner?
EDIT:
Here's a very simplified example. I do have a problem I'm trying to solve, but I'm more interested in understanding the way to do this properly.
Basically, the .ready function in ajaxPage.html is firing before importantDependency.js is completely loaded, so the first load of ajaxPage, importantDependency is missing, but subsequent loads see it.
index.html
...
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$('#myButton').click(function() {
$('<div></div>').dialog({
open: function () {
$(this).load('ajaxPage.html');
}
});
});
});
</script>
...
ajaxPage.html
...
<script type="text/javascript" src="importantDependency.js"></script>
<script type="text/javascript">
$(document).ready() {
$('#thing').leverageImportantDependency();
});
</script>
...
EDIT 2:
I want to do this FROM the loaded content, not from the page calling the content. Modifying the calling page means duplicating code in every instance where this is called. I'd like the behavior to be attached to the content, not the page calling it.
Generally, you will want to do something like this:
$("#container").load(function(html) {
// container has been filled up, and is
// ready for JS processing
doSomethingWithNewContent();
});
That is to say, fire off something once the content has been replaced, by utilizing the appropriate ajax callback. Other examples include:
$.get("foo.html", function(html) {
$("#container").html(html);
$("#container").find(".foo").fancyThing();
});
$.ajax({
url: 'foo.html',
type: 'post',
success: function(html) {
$("#container").html(html).find(".foo").hide();
}
});
See:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.load/
EDIT: From what I understand from your edit, you want attach something, such as a an event handler or a plugin to some elements that keep getting replaced. There are a few ways to do this:
In the success callbacks, as
demonstrated above.
Using .live or
.delegate.
Using .liveQuery.
I'm not sure if I get your question, but when you have retrieved the data, you simply do whatever you want with it in the success handler of the ajax call:
$.ajax({
url: pageUrl,
success: function (data) {
$(".someContainer").html(data);
// TODO: This is your ready handler for the new content
}
});
You could use the complete property of an JQuery Ajax call. The complete function is called after success or error.
$.ajax({
url: "foo",
complete: function({
// I'm done
}
});
See: http://api.jquery.com/jQuery.ajax/
Not sure if I am being totally wrong here but I want to do something like this:
Have an external js page (on an external server)
Include the page - OK that is easy etc...
Have a Jquery function on the external page - well actually many functions
Call those functions directly onto the page.
All a bit like this:
External js page:
$(document).ready(function() {
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_1() {
$('#test_2').load('page_2.php');
}
});
Then on the actual page just call:
<script type="script/javascript">
testit();
</script>
<div id="test"></div>
Am I wrong or should that not work?
You dont need to define the functions within the ready function, but you have to call it within the ready function.
$(document).ready(function() {
testit();
});
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_2() {
$('#test_2').load('page_2.php');
}
Otherwise testit() will be called before the document is loaded. And at that moment the function doesn't even exist yet in your example.
Your functions are local to the scope of the anonymous function passed as the argument to $(document).ready(). Here's a simple example showing the behaviour you're seeing:
(function() {
function foo() {
alert("It shouldn't alert this...");
}
})();
foo();
To fix it, simply move your function declarations outside of the ready function:
function testit() {
$('#test').load('page.php');
}
function testit_1() {
$('#test_1').load('page_1.php');
}
function testit_2() {
$('#test_2').load('page_2.php');
}
And use the ready function (shorthand $(function() { ... })) in your main js file:
$(function() {
testit_1();
});
I'm not sure if I'm understanding you wrongly, but will you load an external page of an external server? This is not possible on normal browser security settings. You cannot perform a succesful XMLHttpRequest for a document that resides on a different server. Nearly all browsers will block this and leave you with nothing. You would have to write a server-side proxy that fetches the document and serves it back to the client.
That should work fine. Just be sure to include the external JS file in your page and execute testit() inside another $.ready() call:
<script type="script/javascript" src="http://someurl.com/external.js"></script>
<script type="script/javascript">
$.ready( function() {
testit();
} );
</script>
<div id="test"></div>
The location of a JS file is irrelevant. Once it is loaded into your page, it is executed in the context of that page.