I have a page(let's call it 1.php) that loads 2.php into a div-box using jQuery-ajax.
2.php prints 20 records from my database.
When I reach the bottom of the div-box when scrolling, I want it to load the next 20 records.
Like Facebook, Twitter, etc, etc does it.
Now, I've gotten this behaviour, but only when loading 2.php on it's own!
But not within the div-box.
How do I go about this?
Thanks in advance!
File 1.php should output this:
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function() {
// when we scroll, check the position:
$(window).scroll(function()
{
// if at bottom, add new content:
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
$.get("2.php",function(data) {
$("#content").append(data);
},'html');
}
});
});
</script>
If you want to send the iteration number to 2.php you could remember it in some hidden input and send it as argument to $.get().
Hope it helps.
You probably have some initialization Javascript code in 2.php to setup the scrolling event handler. This initialization code is not executed when you load the page with ajax and put it inside a div. You will need to execute the same initialization code after processing the Ajax request.
Consider using waypoints plugin for jQuery:
http://imakewebthings.github.com/jquery-waypoints/
And give a look at the Infinite scrolling example:
http://imakewebthings.github.com/jquery-waypoints/infinite-scroll/
The key here is detecting the scroll position. Is this working correctly?
Related
I would like to auto refresh a specific div (with the class 'autotest') every 3 seconds and I use this script to do so:
<div class="autotest">some variable</div>
setInterval(function() {
$('.autotest').load(window.location.href + ' .autotest');
}, 3000);
and it kinda works but it includes the tag upon refreshing so it look like this:
<div class="autotest">
<div class="autotest">some variable</div>
<div class="autotest">some variable</div>
</div>
The first time it refreshes it ends up like above. The next time it refreshes it doesn't add more divs. On each refresh it updates the variable which is good.
What is wrong here?
You need to add a query parameter like "isajax=true" to your request to inform your php code that this is an ajax call and it does not need to include the surrounding div to the output.
In your php file you can simply add an if clause to send different outputs based on the query param:
if (!empty($_GET['isajax']) && $_GET['isajax'] == 'true') {
// response without html tag
} else {
// normal html response
}
Thank you for your help #Alimo. I couldn't get it to work but it was probably me. I decided to put my variable in another page and then simply load that one.
setInterval(function() {
$('.autotest').load('autotest.php');
}, 3000);
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.
Here is my current setup.
I have two pages running on the jquery mobile framework.
index.php
article.php
In bother headers I have a js file called ratings.
here is my js ratings.js:
$(document).ready(function(){
$("#rating_1").click(function () {
$("#rating_2").css('backgroundPosition', '0px 0px');
$(this).css('backgroundPosition', '-45px 0px');
});
});
When I load index.php and then go to article.php none of my triggers to ratings.js work.
If I add rel="external" or data-ajax="false" my triggers work.
However then I lose the ability to have my loader wheel come up.
Any suggestions?
Thanks!
Important: Use $(document).bind('pageinit'), not
$(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as
the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
http://jquerymobile.com/demos/1.1.0/docs/api/events.html
Try:
$(document).bind('pageinit', function() {
$("#rating_1").click(function() {
$("#rating_2").css('backgroundPosition', '0px 0px');
$(this).css('backgroundPosition', '-45px 0px');
});
});
You should put everything inside:
<div id="page" data-role="page">
<!--here-->
</div>
Script in the <head></head> section will not be loaded while ajax loading.
The problem is that jQuery loads pages via Ajax and therefore, it only loads the
<div data-role="page"> </div>
parts of the page.
You can do 3 things to solve this kind of an issue.
1.) The one which you have already tried ( which is to make a data-ajax=false ) which makes your page load completely again and not showing your loader wheel.
2.) You can make the event a live event:
$("#rating_1").live('click', function () {
$("#rating_2").css('backgroundPosition', '0px 0px');
$(this).css('backgroundPosition', '-45px 0px');
});
This will make it look for any new #rating_1 and will add the click event to it.'
3.) Instead of using $(document).ready you can use $( '#myPage' ).live( 'pageinit',function(event){}; function.
Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file
I'm using jQuery to dynamically load php pages into my page using the .load() function, so far this has been successful but if you click on various links to update the div with the .load() it starts to flicker between the new clicked page and the old one, this is pretty annoying and has anyone got a fix?
Current code:
$(document).ready(function(){
$('a').click(function() {
$('#content').load($(this).attr("href"));
return false;
});
});
The flickering is possibly caused because the dimensions of the #content div vary between loads, try to slideTogle it before loading or use another transition between loads
example :
$(document).ready(function(){
$('a').click(function() {
$('#content').slideUp('slow',function(){
$('#content').load($(this).attr("href"),function(data){
$('#content').slideDown('slow');
});
})
return false;
});
});
I hope it is ok to question the premise. You're making all links use ajax to replace #content's contents? Doesn't that break the browser's forward/back button behavior? If so, I personally would not like to use such a site.