$(document).ready(function(){
setInterval(function(){
$('.bopa').load('accounts.php');
},30000);
});
Hi guys! Me again. So I got back to this stuff and I realized that this is JQuery. It maybe possible for me to put a fade effect somewhere there. I just don't konw where. Is it actually possible if so please tell me where. The accounts php actualy contains something like
$command=mysql_query("SELECT * FROM pages order by rand() limit 1");
now it works every 3 seconds the content changes. I am trying it on text first so that it'd be easier. Later on I'm planning to do it on pictures.
You can add a callback function to the AJAX request you're making:
$('.bopa').load('accounts.php');
Could change to:
//start by fading-out the element(s)
$('.bopa').fadeOut(250, function () {
//continue by loading the new content now that the element(s) has/have faded-out
$(this).load('accounts.php', function () {
//now that the new content has loaded, fade the element(s) back in
$(this).fadeIn(250);
});
});
This also takes advantage of the callback functions for the jQuery animation functions used (.fadeIn()/.fadeOut()).
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 know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {
The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.
I am programming an online PHP-based fantasy pet simulation game. I am not very familiar with AJAX, so please keep this in mind when answering.
On pet pages, I would like users to be able to feed/water/play with their pets without needing to reload the entire page - that's why I'm using AJAX. Here's what I have so far:
Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$("#petcareFood").load($(this).attr("href"));
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"));
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$("#petcarePlay").load($(this).attr("href"));
});
});
</script>
Working HTML
<a class=\"petcareFood\" href=\"petcare.php?pet=#&action=#\">Feed Your Pet</a>
<a class=\"petcareWater\" href=\"petcare.php?pet=#&action=#\">Water Your Pet</a>
<a class=\"petcarePlay\" href=\"petcare.php?pet=#&action=#\">Play With Your Pet</a>
NOW, everything that I listed above works like a charm! This is my problem: I want those links to also update another DIV - the one which contains updated status bars showing how hungry/thirsty/unhappy their pet is. Currently, I am doing that like this:
The Almost Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$('#petcareThirst').load('ajax/thirst.php?pet=#');
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$('#petcareMood').load('ajax/mood.php?pet=#');
});
});
The script above makes it so that when a user clicks one of the HTML links, it updates two DIVS (one DIV containing the message displayed when a user feeds/waters/plays with their pet, and the other containing the status bar). Now... that seems all fine well and good, BUT... if both scripts update at exactly same time, then the PHP that handles the status bar is not updated - it's still retrieving old information.
My question to all of you is: Is there any way that I can delay running the second set of script (so that it will update after the PHP makes changes to MySQL)?
I tried inserting this before "the almost working script":
setTimeout(function() {
$('#petcareMood').load('ajax/mood.php?pet=#');
}, 2000);
However, it doesn't work. Well - it does, but just once. Users need to play with their pets at least 3 times a day to achieve 100% happiness, and so delaying the second DIV only once doesn't cut it for me. When I tried adding the same script multiple times, it just stopped working all together. What can I do?!
If you'd like to see screen shots of how things are working, please just ask. I will be happy to provide them upon request.
Thank you in advance!
Instead of a hardcoded delay time, you maybe could use the callback function of the first ajax action:
//trigger first ajax
$("#petcarePlay").load($(this).attr("href"), function(){
//trigger second ajax call, when first is completed
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
see http://api.jquery.com/load/
You could use the complete parameter to specify a callback function that gets executed when the request completes. Then from within the callback, execute another request which actually updates the divs.
Example:
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"), function(response, status, xhr) {
// code here to make another request for stats
}
});
Alternatively, you could have the initial URLs return some JSON data that contain the updated stats so when a person does something to/with their pet, it returns all the stats so you can immediately update the div's all with one call rather than having to make a secondary call for the data.
I'm not sure, but i think the ajax constructor is better for your purpose http://api.jquery.com/jQuery.ajax/.
There you can set that the AJAX will be synchronous(It will wait to finish the AJAX callback )
Here is a few theory about it :)
http://javascript.about.com/od/ajax/a/ajaxasyn.htm
Instead of setTimeout, use setInterval. When it's no longer needed, you can kill it using clearInterval.
setInterval will execute a given function every n milliseconds.
I'm meeting huge problems while creating a rating system for my website.
I have no problem with PHP, but with Javascpit and jQuery.
My intentions are to give the rated value to PHP, and, also give some other variables that are into the page URI (like: ?pg=try&id=2).
Here what I do (and it work) util now:
$(document).ready(function(){
// START the RAtings script
$('.ratingStars').hover(
// Mouse Hover
function() {
$(this).prevAll().andSelf().addClass('overStar');
$(this).nextAll().removeClass('voteStar');
},
// Handle teh mouseout
function() {
$(this).prevAll().andSelf().removeClass('overStar');
set_votes($(this).parent());
}
);
// This make al clicable
$('.ratingStars').bind('click', function() {
////// HERE THE CODE TO PHP
});
});
I also need to know how to pass variables from PHP to Javascript...
Thanks in advice.
You will need to use AJAX to make a request to the backend. Have a look at http://api.jquery.com/jQuery.ajax/