I've got a script in an HTML file that runs a php file every 30 seconds. The php file is intended to change a div's innerHTML. I don't seem to find the way to replace it.
I was using load() but there are several divs I want to keep updating every 30 seconds and I don't want to make the server GET that much requests. So I'm looking for one only php get and then change the innerhtml in those several divs
This is what i've got:
HTML:
<script type="text/javascript">
$(document).ready(function () {
$.get('php.php');
});
setInterval(function(){
$.get('php.php');
}, 30000);
</script>
<div id="foo"></div>
php.php:
document.getElementById("foo").innerHTML = '<?php
// some php code
?>';
I think the problem is I'm not being able to get the element from the parent HTML file. I don't know how to solve this...
Any suggestions will be more than aprecciated!
You are reinventing jQuery's load()
function fetchContent() {
$("#foo").load('php.php');
window.setTimeout(fetchContent, 30000);
}
$(fetchContent);
The server should just return the HTML content that you want to display.
EDIT
Since your comment is different from the original question.
function fetchContent() {
$("#foo").get('php.php', function(data) {
var html = $("<div/>").html(data);
$("#foo").html( html.find("#Section1").html() );
$("#bar").html( html.find("#Section2").html() );
$("#asd").html( html.find("#Section3").html() );
window.setTimeout(fetchContent, 30000);
});
}
$(fetchContent);
You would want to add an onError handler and might want to set the no cache option for the Ajax calls.
what you probably want is for your php.php to return some data, and then you use the success of the $.get to update your #foo; taking an example from http://api.jquery.com/jQuery.get/ and modifying it for your example
$.get("php.php", function( data ) {
$( '#foo' ).html( data );
});
hope that helps :)
Related
I am building a chat. I have this Jquery working code which calls logs.php every second and refreshes the chat.
$(document).ready(
function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {
$('#chatlogs').load('logs.php');
updateScroll();
}, 1000);
}
);
As you can see, also updateScroll, a JS function on my page, gets called. Updatescroll creates a variable, which I would like to pass on to logs.php, is there any way to do this? In other words, updatescroll basically checks everysecond if the user has scrolled up to the top of the chat. If so, I am gonna tell logs.php to load -say - another 10 messages. But in order to do this, I have to have something that from updatescroll passes on to the Jquery function and thus onto logs.php. You get it? Thanks
First, when it comes to ajax, I would recommend using a window.setTimeout, intervals can get tricky when you are running things asynchronously (if one call hangs you can end up with multiple calls to the same script).
so something more like:
(function($){
var update_messages = function(){
var count = updateScroll();
$('#chatlogs').load('logs.php?count='+count, function(){
window.setTimeout(update_messages, 1000);
});
}
$(document).ready(function(){
$.ajaxSetup({cache:false});
update_messages();
});
})(jQuery);
Then in your PHP script the "count" would be available via $_GET['count'].
EDIT: you can see an anonymous function is being sent as a second argument to load, this will be called AFTER the AJAX call is complete, so we can make sure only 1 of these is running at a time
I've got a certain php code in a div which gets data from mysql.I want this div to refresh every minute without refreshing the entire page.
Currently I'm using this, doesn't work well
<div id="abc">
<?php
?>
</div>
window.setTimeout('location.reload()', 60000);
The ideal way to do this is to use jQuery.ajax to retrieve data from your server, and then use JavaScript/jQuery within your success function to update your page.
You can still use setTimeout or equivalent to periodically issue AJAX requests.
As you want to refresh the div content every minute you need to look at setInterval method and load of jQuery:
window.setInterval(function(){
$('#abc').load('PHPFile.php');
}, 1000);
and your PHP script mentioned in the url part of the load method must be capable to provide the result in HTML format which is going to be placed in the given div (id:abc)
Have the PHP-code on another page (for example; loaddata.php) and have a jQuery timer executing a function which loads the page loaddata.php
Loaddata.php
<?php
echo "Hello World!";
?>
index.php
<div id="data"></div>
<script>
$('#div').load("loaddata.php", function() {
window.setInterval("loadData", 60000);
});
function loadData()
{
$('#div').load("loaddata.php");
}
</script>
Something like this:
function refreshContent() {
$.post(urlHere, { data here...}, success(data) {
//...manipulate DOM here...
}
}
setTimeout(refreshContent, 60000);
Example of jQuery Ajax
file1.php
<?php
echo 'PHP content e.g. from database based on submitted request - '.$_POST['my-value'];
?>
file2.html
<div class="content"></div>
Refresh div
<script>
$(function(){
$(".reload-data").click(function(){
$.post("file1.php", {my-value: "something"}, function(data){
$(".content").html(data);
});
});
});
setTimeout(function(){$(".reload-data").click();}, 60000);
</script>
For these situations I sometimes use jQuery.load()
Example from documentation:
<div id="result"></div>
<script type="text/javascript">
function refreshDiv() {
$('#result').load('ajax/test.html #container', function(){ /* callback code here */ });
}
setInterval(refreshDiv, 10000);
</script>
This does the following:
Checks if the #result element is in the current page
If it is, it makes a request to the ajax/test.html page
Grabs the #container from the response, and dumps it into #result
And it does this every 10 seconds
That's about it. One line of code, although not as efficient as a true ajax request, it does the job.
I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});
I want to load the external page's data into a div along with the javascript functions(though the js file is same for both of them, the functions do not work). The file loads fine into the page, but the javascript function don't work properly.
My Code-
var emaild = $("#hidden").val();
var div = $("#mydiv");
var refreshId = setInterval(function() {
$.getScript("js.js", function() {
div.html($("#load").load('posts.php?id='+emaild));
});
}, 6000);
$.ajaxSetup({ cache: false });
Thanks in advance. Hope I get a solution soon! :D
You may have a problem here:
div.html($("#load").load('posts.php?id='+emaild));
$.html() expects an html string and you're giving it a deferred instead. It may not be the cause of your script not running, but good to eliminate anyhow.
Is there a reason why you're using $("#load").load when you want the output of the call to go inside div. In other words, isn't this what you really want?
div.load('posts.php?id=' + emaild);
There's a great tutorial on IBM's website which walked me through a simple search/results list using jQuery,PHP and Ajax.
I was able to make it work and it's really cool.
One problem. I want the results to be hyperlinks and I can't get any java script to run on the results.
Here is the script I have (includes what was in the tutorial plus the additional script necessary to ovverride the hyperlink, click behavior):
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
$("a").click(ClickInterceptor);
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
function ClickInterceptor(e)
{
window.alert("Hellow World!");
return false;
}
</script>
If i put the following html under the <body> tag:
this will work
That will display the alert window.
However, if I change the results to hyperlinks (found in find.php, listing 7 from the tutorial):
$string .= "".$row->name." - ";
It does not work.
Any idea on how to fix this?
The click function binds when it is run. You need to change it to a live binding.
$("a").live("click", ClickInterceptor);
Or you can just bind it when you update the search results by putting the following after $("#search_results").html(data):
$("#search_results a").click(ClickInterceptor);
The problem is pretty simple actually, $("a").click(ClickInterceptor); will only look for items that currently exist in the DOM. All you need to do is change that line to this:
$("a").live("click", ClickInterceptor);
I'd also advise taking the time to read more about jQuery's Events/live.