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");
});
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 am developing a web app that has some messages. In the menu, I have displayed the message number as follows.
<ul class="menu">
<li>Messages <span id="count" class="pull-right">3</span></li>
</ul>
On the other hand I have a php file that outputs only the message count. I want to update span#count using this php file on click of a button with class .jm-msg
I have jquery loaded on my page. As I am very new to AJAX and Javascript, I have absolutely no clue on how to do this. Can someone please guide me by providing sample code?
This is pretty easy:
setInterval(function(){
$.post("yoururl", function(resp){
$("yourspanid").html(resp);
});
}, 1000)
Your url needs to be set to the file where you load the data from
If you want to keep the span data uptodate simply use setInterval().
You should use setInterval over your whole $.post not just the function
This is a one-liner:
$('.jm-msg').on('click', function() {
$("#count").load('/getCount.php');
});
Documentation: http://api.jquery.com/load/
I have a simple PHP file with some HTML (got a list in the form of UL>LI>UL>LI, which uses the toggle() function. The function opens the ULs and shows or hides the LIs). The page also has an input form that works correctly (adds data to the database).
Once the AJAX form has been successful, I delete the entire div and reprint it from the database.
My problem: once the new page is printed, the toggle() function stops working until the page is refreshed.
The toggle function (in external JavaScript file):
$(document).ready(function() {
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
});
The form:
<form id="addPForm">
<section id="product_input">
<input id="list_add_product" type="text" placeholder="Add a new product" onkeyup="checkProducts()">
<input id="list_add_product_button" type="button">
</section>
</form>
The form sending function:
$("#list_add_product_button").click(function(event){
var txt=$("#list_add_product").val();
$.ajax({
type: "POST",
url: "addproduct2.php",
cache: false,
data: {product: txt},
success: onSuccess,
error: onError
});
// IF THE SUBMIT WAS SUCCESFULL //
function onSuccess(data, status)
{
console.log(data);
clearInput();
$('#main_list').empty();
$('#main_list').html(data);
}
function onError(data,status){
// something
}
});
What I get printed in the console.log(data):
<div class="product_category"><li id="baked" onclick="showBakedList();"><a class="list_text" id="baked_text">Baked [2]</a></li><ul id="ul_baked" class="inner_list"><li class="product" id="bread"><a class="liText">Bread | 0 Unit</a> </li><li class="product" id="croissant"><a class="liText">Croissant | 0 Unit</a> </li></ul>
Now, the toggle() function works great before I add a product. The lists opens and closes without any problems. I do not get any errors in the console and I load jQuery in the page head (first item).
I would like to note that looking at the source code before and after the code print looks exactly the same, except the new additional LI that is printed.
Am I missing something? Do jQuery functions stop working after a div data refresh?
If your element is been removed after click event binding, it will not call the event handler function.
Use $.on() insted of .click():
$(document).on('click', '.product_category', function(event) {
// Your function here
}
Explained:
$(".product_category").click() binda a function to the .product_category elements at that moment. If one or all elements are removed, then the event bind also will be removed.
$(document).on() will bind an event to entire document, and will filter every click to check if the click occurred in a '.product_category' element.
Try this:
$(document).ready(function() {
checkForDOMElements();
});
And a function...
function checkForDOMElements(){
$(".product_category").click(function(event) {
event.preventDefault();
$(this).find("ul > .product").toggle();
});
}
In your AJAX request, after success add:
checkForDOMElements();
Does this work for you?
The main problem is this:
When you load page you have one DOM tree with all elements. Javascript save this DOM. After this you remove all elements from DOM tree and load new. But for javascript the elements are only removed and js can't detect new elements for your toogle() function..
You have to reload javascript function to refresh new DOM tree (new HTML) with new elements.
I found this solution while having the exact same problem. I am building a complex webtool that uses Ajax/JSON that contains HTML with JS events built into the JSON.
To be more fine grained on the calls, I wrapped each specific JS event that had to do with the specific Ajax/JSON HTML replace and call it on load as well as after the AJAX success.
If there is a more "up to date" way of doing this, I would love to hear about it, but this worked GREAT for me.
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.
Goal: I'm trying to refresh content inside a div so that if the user is logged in, the page changes dynamically.
Progress: My first attempt was to use $("#tab_b").load("php/tabs.php #tab_b"); but this didn't update the DOM so the jquery styling didn't get applied. Then I tried adding the .trigger('create') function $("#tab_b").trigger('create'); This only led the style blink on and off for a fraction of a sec. Then I tried the .append() function which seems to work, I'm using the following code to test the function and this works:
$("#tab_b").html('');
$("#tab_b").append("<button type='submit' data-theme='a'>Test button</button>").trigger('create');
the only problem I have is fetching the content from the php file and then appending it to the div.
Content that should be refreshed: " #tab_b "
<div id="tab_b" class="content_div">
<?php
if(!isLoggedIn())
{
...
}
else
{
echo("
<button type='submit' data-theme='a' id='logout' >Logout</button>
");
}
?>
</div>
Any idea's on how to do this? Also Any suggestions on improvements are welcome, I'm a beginner programmer.
This question is an attempt to solve a bigger problem discussed in my other topic:
jQuery Mobile does not apply styles after dynamically loading content
this might work:
$( '#tab_b' ).live( 'pageinit',function(event){
alert( 'This page was just enhanced by jQuery Mobile!' );
});
I would look into the Event API
http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/events.html
I found that you can fetch data with $.ajax function. This returns the whole page.
My solution was to move the content that needed to be refreshed to a new php page,
tab_b.php and load it from there. Not sure if this is the best solution but it works.
$.ajax({
url: 'php/tab_b.php',
success: function (data) {
$("#tab_b").html('');
$("#tab_b").append(data).trigger('create');
}
});