I'm creating a system using jquery and php that pops up a small div when they get a private message on my website. The alert itself I have figured out, but I'm not sure how to gracefully cancel it.
I've made it so that clicking a link "[x]" hides the div, but how can I make the link send enough information to a php script to mark this alert as "read" in the database?
All the php script would need is the id of the alert in the database, but I've got no idea how to make it do that. There is also more than one notice displayed at a time, so I would need a way to have each link send the information necessary to the php script.
Here's the jquery that loads the div and the php that powers it.
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#mc').load('/lib/message_center.php').show("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.delete').live('click', function(){
$('#mc').hide('slow');
});
});
</script>
The easiest solution would be to set the message you are displaying to read at the moment you display it. That would not require any additional communication between the browser and the server, just do it at the end of your /lib/message_center.php script for the messages you are displaying at that moment.
Set the href attribute for your X produced by php like href="javascript:killbox(5);" and give your div a unique id (i.e.id="boxtokill5"). Then you could use something like this:
function killbox(id){
$("#boxtokill"+id).hide();
var packet = {};
packet.clickedlinkid = id;
$.get("destination.php",packet,function(data){
// data = Response (output) from script
});
}
The destination.php receives the ID by $_GET['clickedlink'].
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'm using the code below to load the results from a database query in a PHP page:
click me
$('.item > a').click(function(){
var url = $(this).attr('href');
$('.item-popup').fadeIn('slow');
$('.item-content').load(url);
return false;
});
All works fine right now, but the next bit of functionality is a problem. Inside results.php which ajax loads into .item-content, I have another link that is supposed to update and increment click counts for that link, also without refreshing. The functional PHP bits all work fine. My only problem is the jQuery/AJAX aspect of things.
Maybe I'm going about it the wrong way, but what I really want to do is have a page with a container that loads the result of of a database query from a PHP page, but also in that container, I have a link/button whose click count I want to be able to save and update all without refreshing.
EDIT
I guess the most important question I need answering is: When the ajax on index.php loads the content of results.php into the container in index.php, do browsers treat the newly loaded ajax content as part of the parent page (index.php) or is it still treated as a different page loaded into the container like an iFrame?
If say for example it is click event then you need to write
$('input element').on('click',function() {
// write code over here
})
Dont know for sure if you want this, When returning the data in the load function you will have to add a link like this in the resultant HTML which will be clickable:
Now in javascript you need to catch the click event of the link like this:
<script type="text/javascript">
$(function(){
$(".item-content").on("click", ".clickable", function(){
var counter = $(this).data('counter');
var id = $(this).data('id');
$.ajax({
url : //your url here,
data : {'id' : id, 'counter' : counter },
type : 'POST',
success : function(resp){
//update the counter of the current link
$(this).data('counter', parseInt( $(this).data('counter') )+1 );
//whatever here on successfull calling of ajax request
},
error : function(resp){
}
});
});
});
</script>
I've got a dynamic table filled by a recordset from MYSQL.
Each row has it's own delete button (image) to delete the specific row.
This button has a class="button".
I'm using a JQuery popup modal to get a popup when a delete button is clicked.
In this JQuery script i'm creating a variable which contains the numeric value of the first td cel of the row that has been clicked on.
This all works perfectly.
What i'm trying to accomplish is to use this variable on the same php page.
Here is where my knowledge runs out.
I've read some examples where Ajax is the solution for this, but i lack the knowledge to use these examples for this solution.
JQuery code:
<script src="../javascript/jquery-1.8.2.js"></script>
<script src="../javascript/jquery.reveal.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function(e) { // Button which will activate our modal
var value=$(this).closest('tr').children('td:first').text();
alert(value); // this works
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
});
</script>
I've been trying too much that i don't see the logic anymore.
I hope that someone can help me with this.
The issue is that your JavaScript runs in the client -- the user's web browser -- while your PHP runs on your server. It's a two-stage process: first, all the PHP is executed on the server and the HTML is rendered, which is then sent to the client (the browser). Then, the client executes all the JavaScript on the page.
You need some way to communicate the JS variable (value) to your server if you want to be able to use it in your PHP code. AJAX is one such way, but it would be helpful to have more information on how exactly you want to use this information in your PHP.
Edit: based on your comments above, something like this should work. You'll have to give your Yes button an id attribute (here I'm assuming the id is yesButton).
$(.button).click(function() {
var value=$(this).closest('tr').children('td:first').text();
$("#yesButton").attr("href", "delete_verlof.php?id=" + value);
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
The important thing to note is that the JS variable does not exist yet at the time at which your PHP executes, so it is not available to the PHP. What I've done here instead is to dynamically change the href of the Yes button whenever the user clicks a td, which should have the desired effect.
If your using this in a form, then you could create a hidden input field with a unique id and add it with.
$('#idOfField').val(value);
And then use php to get the element from wherever you put it in your code.
Other then you might find attr usefull. For an example
$('#idOfField').attr('data-id', value);
Where the ID can be an div, span, i, a, bold, strong etc etc etc.
This would be a common question but what I'm looking for is:
My PHP Script does:
Read a remote page using cURL
Update every 20 Seconds
I want to auto update a div(Not whole page), (Which is populated using cURL) every 20 seconds.
I've read many solutions but that doesn't show updated data in source code (Crawl-able form).
Pls suggest me a solution how to update a div with cURL updated data, and that should populate/include in my page's source code.
Let me know if anything is unclear. sorry for bad english :(
Copy your cURL PHP codes into a new file named "reloader.php", in your main page, also put the source codes which reads the data(cURL stuff) in a div "id = to_be_reloaded", in your main page add these:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#to_be_reloaded').load('reloader.php').fadeIn("slow");
}, 20000); // refresh every 20000 milliseconds(20 seconds)
</script>
I know you need it for commenting system and
The workaround is use setInterval like this:
<script type="text/javascript">
setInterval(function(){
$.ajax({
url:'PUT YOUR URL',
success:function(data){
$('#comment').append($(data).fadeIn());
}
});
}, 20000);
</script>
Anything else ...
good luck
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.