Jquery - auto refresh specific div on page - php

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);

Related

Loading results of PHP function into DIV container

It seems this question has been answered in the past, however, I'm either 1) having a hard time grasping the solutions or 2) not implementing them correctly.
I have a PHP function, that when run, will return results of a database query. Results look similar to this:
Koenji
I can echo this into a page just fine. What I'd like to do is give an end user the option to refresh the link (which can be done by refreshing the page and echoing a new random string returned by the php function) without having to refresh the whole page. I've tried a few different methods, but it seems the function that returns the element is only run when the page reloads - so my URL never changes.
Here is my latest attempt. I figured the url I'm grabbing from the database was only getting set when the paged loaded. I thought setting a function to initialize the url variable would help - no good. It still only works once on page load.
$(document).ready(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
$('#clicky').click(function() {
updateVariable();
$('#dannychoolink').html(random + url);
$('.danny-choo').attr('target', '_blank');
});
function updateVariable() {
url = '<?php echo dannyChoo();?>';
random = 'Random DannyChoo.com article: ';
};
You can see it live at www.dannychoofan.com.
Any help is appreciated =0)
It looks like your looking for an ajax style call.
You should put the contents of the dannyChoo() function into a new file called articleLinkGenerator.php at the same level as your index.php file. This file should have the contents of the dannyChoo() function so that it automatically executes and echos the html you are expecting for the link like
<?php
function dannyChoo(){
// generate random link code
echo $random_link_html // Like Koenji
}
dannyChoo();
Then in your index.php (main web site) update your functions using ajax(http://api.jquery.com/jQuery.get/) to look like:
$(document).ready(function() {
updateVariable();
});
$('#clicky').click(function() {
updateVariable();
});
function updateVariable() {
$.get('articleLinkGenerator.php',function(data){
$('#dannychoolink').html(data);
});
};
It's because PHP runs before the page loads, and JavaScript runs after the page loads, so your variable never changes without another page load.

CSS Notifications fade

Im creating a small web app and I have used AJAX in a few functions such a creating and deleting certain objects.
To notify the user I have used PHP to echo a HTML notification on to the screen depending on weather the object was successfully created or not.
if ($query) {
//response to ajax call if successful
echo '<div class="alert alert-success"><a class="close" data-dismiss="alert">×</a><h4 class="alert-heading">Success!</h4>Object Added!</div>';
}
The problem is, over time the notifications build up on the screen as there is no refresh to remove them.
I have a jQuery function that can remove the alerts every 5 seconds shown below
function clearAlerts(){
setTimeout(function() {
$('.alert').fadeOut('fast');
}, 5000);
}
But I dont know how to call this function every time a notification is added to the page, is
there anyway to use jQuery to perhaps detect when a notification has been echoed on to the page, or to run this jQuery function each time they are added.
Thanks
Put this tag directly inside each HTML snippet you are generating, you can style it in any way you like:
<span class="close-notification">Close</span>
Then use this piece of JS to remove it when clicked.
$(document).on('click', '.close-notification', function(){
$(this).parent().fadeOut(); // could use .remove(), .slideUp() etc
});
What you want is possible, by jQuery. First, add a class to the notification div, for example:
<div class="notification">Notification</div>
Then this jQuery:
$(".notification").live("ready", function(){
$(".notification").setDelay(5000).fadeOut("slow");
});

Load div from another page within an AJAX loaded page

I'm using jQuery address to enable loading specific content from other pages
and to change the URL in the address bar.
I'm working on a little Social Network alike website, so I'm reading out the IDs
of the posts table of my MySQL database via PHP. I want to use the possibilities of jQuery and AJAX to read everything out dynamically.
I found out, that I have to use live() (which turned out to be old), delegate() (which
also turned out to be old in 1.7.1) or on() (which turns out to be the best possibility
to make events work inside of dynamically loaded content via jQuery + AJAX).
I also read somewhere, that I can't use load() or get() to load new content from another
page inside of an already loaded content, because it doesn't "bubble" (I don't even know
what that means).
What do I have to do to load new content within an AJAX loaded page?
Here's a snippet I tried to work with (included on the loaded page):
<?php
if(exist('`posts`')) {
$load = mysql_query('SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 10');
while($row = mysql_fetch_object($load)) {
?>
<script type="text/javascript">
$('body').on('body', 'load', function() {
$.get('getpost.php', { pid: <?= $row->id ?> }, function (data) {
$('#posts').html($('#post_<?= $row->id ?>', data).html()).show();
});
$('#posts').off('load');
});
</script>
<?php
}
}
else {
?>
<div align="center">No posts yet.</div>
<?php
}
?>
getpost.php is my file from which I can get the div_$row->id so that it appears on the start page.
PLUS (Just adding for your knowledge) I want the content to load the content without
a mouseover, click or blur event.
Thanks.
You want to use ".live()" if you want a particular event mapping to be applied dynamically to any new DOM elements which match its selector. Alternatively, you can attach the behavior to each chunk of content loaded.
Write and develop your ajax load independently of your DB lookup to make things simpler. The following snippet triggers another ajax call after each element loads.
<?php
$id = 'div'.mt_rand();
$counter = isset($_REQUEST['counter']) ? $_REQUEST['counter'] : 0;
$next = $counter + 1;
echo <<<END
<div id="{$id}">{$counter}
<script>
$(function() {
$.ajax('/url?counter={$next}', function(html) {
$(html).appendTo($('#{$id}').parent()); // or whatever your favorite method is for adding a sibling
});
});
</script>
</div>
END;
?>
Am I the only one who thinks that this approach is completely wrong? You're making an ajax request for each post, this could end up in making way too much requests, heavily slowing down the loading time. I can't see any reason why you don't want to directly write the posts' HTML inside the PHP while loop.

Infinite scrolling within ajax-loaded page

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?

How do I slide(scroll) an entire div thats been retrieved through jquery's .load()?

So I have I this javascript that loads into a div the contents of my php (which gets data from a mysql database). When a different button is clicked, it calls the eat.php file again, with the new data to retrieve from MySQL and again loads the new data into the div.
<script type="text/javascript">
$(function() {
$("a[name=eat]").click(function() {
$("div.nav a[name=eat]").css({"background-color":"#666966","color":"#fff"});
$(".user-main").load("eat.php");
});
$("a[name=analyze]").click(function() {
$(".user-main").load("eat.php",{ name: "John", time: "2pm" });
});
});
</script>
And that is ok and everything. My question is how can I make this "slide" into the new div, like it's being scrolled horizontally? I am having no luck with the animate feature in jQuery, and would prefer not to use any frameworks. Also, is the correct way to check for a jQuery post by doing:
if (isset($_POST['name']))
in my eat.php file?
I am not quite sure what you are asking.
If you want to ensure the data you have just added is scrolled into view, then you can use code like this
if (document.all) {
document.body.scrollIntoView(false);
} else {
document.body.insertAdjacentHTML('beforeEnd','<a name="' + a + '"><\/a>');
window.location.hash = '#'+a;
}
The trick with insertAdjacentHTML is inserting a label into the screen and then telling the browser to jump to it. The label is the contents of a javascript variable which must be different each time the code is run.
If you wish to slide a whole division into view, then you will have to use a timer. Set up the div so the over-flow is hidden and it is positioned off screen, using position relative and large top or left/right values. Then, each time the timer goes off, decrease the offset towards zero.
If the timer goes off every 50ms and you move only a few pixels, you will get 20fps and it will appear quite smooth.

Categories