I'm trying to put web notifications in the title/tab screen of my webpage. So whenever someone new says something and you're not on the tab, the will give notifications that you have a new message.
Is there any simple way to go about this?
Here's a live link of the chat
would i have to tamper with my post.php? or would
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'> C:\Users\<b>".$_SESSION['name']."></b> ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
or would i tamper with the input ?
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
thanks in advance for any help
!
I'd suggest you to have a look at the JavaScript function setInterval(). Make this function check for updates every x ms, if it finds any updates; edit the page-title.
Something like this should do the trick, tweak to get preferred result:
// This function will run every ~1s
setInterval(function() {
// Get the new data
$.post('post.php', function(data) {
// Handle the data
document.title = data;
});
}, 1000);
You should definitely add some error checking on the PHP-script (check if variables are set: isset($_SESSION['value'])), possibly at the javascript too.
see "document.title" in javascript.
var xarray = ['Someone Posted','Someone else posted'];
var i = 0;
function changeTitle(data){
document.title = data;
}
function changeEvery5Seconds()
{
i++;
i = i%2;
changeTitle(xarray[i]);
setTimeout("changeEvery5Seconds();",5000);
}
changeEvery5Seconds();
Related
So I have been working on this for hours now, I have read a bunch of StackOverflow posts and I am still having no luck.
I have a page that has 2 sections to it, depending on the int in the database will depend on which section is being displayed at which time.
My goal is to have the page look to see if the database status has changed from the current one and if it has then refresh the page, if not then do nothing but re-run every 10 seconds.
I run PHP at the top of my page that gets the int from the database
$online_status = Online_status::find_by_id(1);
I then use HTML to load the status into something that jquery can access
<input type="hidden" id="statusID" value="<?php echo $online_status->status; ?>">
<span id="result"></span>
So at the bottom of my page, I added some jquery and ajax
$(document).ready(function(){
$(function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$newResult = $('#result').html(data);
window.setInterval(function(){
liveCheck();
}, 10000);
}
}
});
});
liveCheck();
});
this then goes to another PHP page that runs the following code
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
echo "<script>location.reload();</script>";
}else{
}
}
the jquery then loads into the HTML section with the id of "result" as shown earlier. I know this is a very bad way to do this, and as a result, it will work at the beginning but the longer you leave it on the page the slower the page gets, till it just freezes.
If anyone is able to point me towards a proper method I would be very grateful.
Thank you!!
js:
(function(){
function liveCheck(){
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST',
success:function(data){
if(data.trim() == ''){
location.reload();
}else{
$('#result').html(data);
window.setTimeout(function(){
liveCheck();
}, 10000);
}
}
});
}
$(function(){
liveCheck();
});
})(jQuery)
php:
<?php
if(isset($_POST['search'])){
$current_status = $_POST['search'];
$online_status = Online_status::find_by_id(1);
if($current_status != $online_status->status){
$data = '';
}else{
$data = 'some html';
}
echo $data;
}
Your page is slowing down because you are creating a new interval every time you call the liveCheck function. Over time, you have many intervals running and sending requests to your PHP file concurrently. You can verify this behavior by opening the developer console in your browser and monitoring the Network tab.
What you should do instead is set the interval once, and perform the $.ajax call inside that interval. Additionally, it's good practice to not send a new request if a current request is pending, by implementing a boolean state variable that is true while an request is pending and false when that request completes.
It looks like the intended behavior of your function is to just reload the page when the $online_status->status changes, is that correct? If so, change your PHP to just echo true or 1 (anything really) and rewrite your JS as:
function liveCheck() {
if (liveCheckPending == true)
return;
liveCheckPending = true;
var search = $('#statusID').val();
$.ajax({
url:'check_live.php',
data:{search:search},
type:'POST'
}).done(function(data){
if (!data.error)
location.reload();
}).always(function(data){
liveCheckPending = false;
});
}
var liveCheckPending = false;
setInterval(liveCheck, 10000);
I have PHP site with MySql data base
I just added automatic save for a text area
and one of the users received the following error:
Too many connections in ...Unable to connect to database
maybe I have to change my ajax auto save:
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
in the page "ajax_for_auto_save_interview.php" I`m including the connection to the DB.
First thing is you should close your mysql connection every time you open it after your usage.
You can have a javascript variable to check whether an AJAX call is already issued and is it finished or not. Only if it is finished, you can re-issue new call
Like this:
var isAjaxStarted = 0;
bkLib.onDomLoaded(function(){
var myEditor = new nicEditor({iconsPath : 'include/nicEdit/nicEditorIcons.gif'}).panelInstance('area1');
if(isAjaxStarted == 0)
auto_save_func(myEditor);
});
function auto_save_func(myEditor)
{
isAjaxStarted = 1;
draft_content=myEditor.instanceById('area1').getContent();
int_id='<?=$_GET[interview_id]?>';
$.post("ajax_for_auto_save_interview.php", { interview_id: int_id,content:draft_content},
function(data){ isAjaxStarted = 0; });
setTimeout( function() { auto_sav_func(myEditor); }, 100);
}
maybe I am writing late you help in place it? thank you very much
<script type="text/javascript">
bkLib.onDomLoaded(function() {
var myNicEditor = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','left','center','right','justify',/*'ol','ul',*/'forecolor',/*'fontSize','fontFamily',*//*'fontFormat',*//*'indent','outdent',*/'image','upload','link','unlink'/*,'bgcolor'*/,'hr','removeformat', 'youTube'/*,'subscript','superscript'*/],/*fullPanel : true,*/
iconsPath : '<? echo "".$IndirizzoPagina."".$IndirizzoCartella."";?>default/image/EditorDiTesto/nicEditorIcons.gif'});
myNicEditor.setPanel('myNicPanel'); //PANNELLO DI CONTROLLO
myNicEditor.addInstance('titolo'); //TITOLO
myNicEditor.addInstance('contenuto'); //CONTENUTO
});
<textarea name='contenuto' id='contenuto' class='box2'>".$ContenutoNotizia."</textarea>"
i used this code http://nicedit.com/
If NewMessage changes, I want an alert. I have tried live and change on and bind change, but nothing works.
Relevant PHP:
$message=6;
$myReturnData["Message"] = $message;
//JSON-encode and return
print json_encode($myReturnData);
Relevant jQuery:
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';}
$(NewMessage).live("change", function() {
alert(NewMessage);
});
});
}, 3000);
'change' is not doing what you think it should be. You should store the original message in a variable, then compare it to the new message you're getting. Like this:
var currentMessage = '';
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';
if (currentMessage !== NewMessage) {
alert(NewMessage);
currentMessage = NewMessage;
}
}
});
}, 3000);
Assuming you want function X to run when a variable controlled by the server changes. To that means you are using a polling mechanism.
So if you want your code to know when it receives a different message, you must store the previous message somewhere outside the scope of your callback function.
Most easy way:
var lastMessage = 'the server will never ever forever ever return this message';
setInterval(function(){
$.getJSON("foo.php", function(data){
// .. arbitrary code
if (lastMessage != data.Message)
{
alert('it changed');
lastMessage = data.Message;
}
// .. more arbitrary code
});
}, 3000);
i don't think the following code makes any sense or would even remotely work, because the NewMessage is not a DOM element, is it?
$(NewMessage).live("change", function() {
alert(NewMessage);
});
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
I have again a little problem with a javascript (i am a real noob regardin that). This time I would like to load an AJAX function on page load in order to save some javascript variables to php sessions. I figured out thats the best way to pass javascript vars to php. If there is a better way (besides cookies), dont hesitate to let me know :)
For now I would like to:
-pass javascript variables to an external php page on page load
-save variables in php
-use the php variables without pagereload
Here is my script so far:
$(document).ready(function () {
function save_visitor_details() {
$(function() {
var visitor_country = geoip_country_name();
var visitor_region = geoip_region_name();
var visitor_lat = geoip_latitude();
var visitor_lon = geoip_longitude();
var visitor_city = geoip_city();
var visitor_zip = geoip_postal_code();
var dataString = 'visitor_country='+ visitor_country +'&visitor_region='+ visitor_region +'&visitor_lat='+ visitor_lat +'&visitor_lon='+ visitor_lon +'&visitor_city='+ visitor_city +'&visitor_zip='+ visitor_zip;
$.ajax({
type: "POST",
url: "inc/visitor_details.php",
data: dataString,
success: function(res) {
alert ("saved");
//$('#result').html(res);<-- should contain variables from inc/visitor_details.php
});
}
});
return false;
}
});
Thanks in advance!
Edit: I changed it a little and got it to work by adding the javascript variables into a hidden form, submit the form with the ajax script above and save variables into php session array at the backend php file.Thanks any1 for your time!!!
I don't really understand what is the question here. But here are a few advices.
rather than serializing the data yourself, you should rather let jQuery do that for you:
$.post('inc/visitor_details.php', {country: geoip_country_name() /* stuff */}, function(data) {
alert('ok!'); alert(data);
});
be aware that, by passing data to your server using Javascript, users can send whatever data they want, including fake data. So handle it with care.
Then entire process may looks like this:
/* javascript */
$(document).ready(function() {
function save_visitor_details() {
$.post('inc/visitor_details.php', {
country: geoip_country_name(),
region: geoip_region_name(),
lat: geoip_latitude(),
lon: geoip_longitude(),
city: geoip_city(),
zip: geoip_postal_code()
}, function(data) {
/* do whatever you want here */
alert(data);
}, 'json');
}
save_visitor_details();
});
/* PHP */
<?php
$keys = array('country', 'region', 'lat', 'lon', 'city', 'zip');
$output = array();
foreach($keys as $key) {
do_some_stuff($_POST[$key]);
$output[$key] = $_POST[$key];
}
header('Content-type: text/plain; charset=utf-8');
echo json_encode($output);
?>
JavaScript:
var http = createRequestObject() ;
function createRequestObject(){
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(str){
http.open('get', str);
http.onreadystatechange = handleResponse;
http.send(null);
}
sendReq("someurl?var=yourvar");
Php:
$var = $_GET['var']; // use some security here.