Jump to content

Website and update parts of it (etc notification on this page)

Joveice
Go to solution Solved by leonfagan71,
1 minute ago, Joveice said:

Is is better to include the scripts or keep them in teh same file? (I like to keep stuff on one location to use for more stuff)

if you will be using the script on multiple pages, you can have the functions in a separate JS file.

but you'd call the function in the actual page.


Cheers,

Leon.

Hi, So I have a page with a notification icon in the top, it also has a badge over it with numbers of notifications found in the database for that user (refresh the page and it will update if there is a new notification) Now how can I  have it update etc every 30 sec? or every min?

Where can I learn about this or find a snippet that works for most things?

I know nothing about how this works and would be really happy if someone could tell me about it or point me in the right direction :)

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, Joveice said:

Hi, So I have a page with a notification icon in the top, it also has a badge over it with numbers of notifications found in the database for that user (refresh the page and it will update if there is a new notification) Now how can I  have it update etc every 30 sec? or every min?

Where can I learn about this or find a snippet that works for most things?

I know nothing about how this works and would be really happy if someone could tell me about it or point me in the right direction :)

You'd need to do this with Javascript. 

Basically you'd need a script on the server that returns JSON or the content of the notification area.

 

Then you can use either vanilla javascript or use the JQuery library to send a GET request, this will then return the content and you'd load it into the notification area div :)

Please let me know if you need any help and I'll provide some scripts for this.

 

Cheers,

Leon.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, leonfagan71 said:

You'd need to do this with Javascript. 

Basically you'd need a script on the server that returns JSON or the content of the notification area.

 

Then you can use either vanilla javascript or use the JQuery library to send a GET request, this will then return the content and you'd load it into the notification area div :)

Please let me know if you need any help and I'll provide some scripts for this.

 

Cheers,

Leon.

Thanks so far :)

I would be happy if you could explain a basic setup on this, like how does it get the values and such. If it's too much to ask for then a link to a basic example? (since my google search turned up nothing)

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Joveice said:

Thanks so far :)

I would be happy if you could explain a basic setup on this, like how does it get the values and such. If it's too much to ask for then a link to a basic example? (since my google search turned up nothing)

 

use PHP to pull information that returns JSON, then use javascript with a set time out to loop every n seconds. javascript would then update the section with the new data.

 

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Joveice said:

Thanks so far :)

I would be happy if you could explain a basic setup on this, like how does it get the values and such. If it's too much to ask for then a link to a basic example? (since my google search turned up nothing)

Of course.

 

You'd need a PHP script to return either the notification area HTML or the JSON data.

I'm not sure what you have in place already so I'll improvise.

$sql=mysqli_query($link, "SELECT `notification_content`, `notification_datetime`, `notification_subject` FROM `notifications` WHERE `user_id`='4757'");
$jsonarray=[];
while ($r=mysqli_fetch_assoc($sql)){
	$jsonarray["notifications"][]=$r;
}

print json_encode($jsonarray);

the json content may be something along the lines of

{"notifications": [0:{"notification_content":"Hello world!", "notification_subject":"I am sparta", "notification_datetime":"2016-12-05 17:21:00"}]}

I can't remember exactly as I'm going off of the top of my head, please could you append that PHP script and send it to me removing any important data.

Then I can work on the java script side.

 

BEWARE that this script doesn't have any checking and is made from the top of my head.

 

Link to comment
Share on other sites

Link to post
Share on other sites

28 minutes ago, leonfagan71 said:

Of course.

 

You'd need a PHP script to return either the notification area HTML or the JSON data.

I'm not sure what you have in place already so I'll improvise.


$sql=mysqli_query($link, "SELECT `notification_content`, `notification_datetime`, `notification_subject` FROM `notifications` WHERE `user_id`='4757'");
$jsonarray=[];
while ($r=mysqli_fetch_assoc($sql)){
	$jsonarray["notifications"][]=$r;
}

print json_encode($jsonarray);

the json content may be something along the lines of

{"notifications": [0:{"notification_content":"Hello world!", "notification_subject":"I am sparta", "notification_datetime":"2016-12-05 17:21:00"}]}

I can't remember exactly as I'm going off of the top of my head, please could you append that PHP script and send it to me removing any important data.

Then I can work on the java script side.

 

BEWARE that this script doesn't have any checking and is made from the top of my head.

 

 
 

Don't waste time looping just encode straight to JSON

json_encode($sql);

I would add a check to see that count is > 1 so you are not returning an empty array.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, vorticalbox said:

Don't waste time looping just encode stright to json


json_encode($sql);

I would add a check to see if count is > 1 so you're not returning nothing.

Didn't realise that it was possible to do that but I always mess about with the fields before doing anything like this so I don't really have much of a use.

Thanks though.

 

The idea for the array is so that I can get a returned row count from PHP and add that to the array like::

{"notifications": [0:{"notification_content":"Hello world!", "notification_subject":"I am sparta", "notification_datetime":"2016-12-05 17:21:00"}], "count":2}

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Joveice said:

Thanks so far :)

I would be happy if you could explain a basic setup on this, like how does it get the values and such. If it's too much to ask for then a link to a basic example? (since my google search turned up nothing)

I've made a JS fiddle quickly.

http://jsfiddle.net/ew9o9b1q/

bear in mind that this is an example and has no security in it...

the JSON content is coming off of my webserver that has no cert so you need to load JSFIDDLE in plain HTTP for this to work.

My webserver is randomly picking the amount of notifications it shows.

it shows a random amount of notifications between 1 and 10 every time the page is loaded.

http://lhdns.cc.nf/cause_i_can/json.php

 

Link to comment
Share on other sites

Link to post
Share on other sites

The cheatiest way of doing it is with a setInterval to carry out a GET request, but the best way is with websockets.

Eien nante naito iikitte shimattar  /  Amarinimo sabishikute setsunai deshou
Dare mo ga hontou wa shinjitai kedo  /  Uragirarere ba fukaku kizu tsuite shimau mono

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, Crowes said:

The cheatiest way of doing it is with a setInterval to carry out a GET request, but the best way is with websockets.

 

8 minutes ago, Clechay said:

You may want to learn about sockets 

If possible include links to how this can be done?

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

setInterval(function() {

	var x = new XMLHttpRequest()
	x.open("linkto.json", true)
	x.send()

}, 10000)

(Roughly)

 

More:

 

http://www.w3schools.com/jsref/met_win_setinterval.asp

http://www.w3schools.com/xml/xml_http.asp

Eien nante naito iikitte shimattar  /  Amarinimo sabishikute setsunai deshou
Dare mo ga hontou wa shinjitai kedo  /  Uragirarere ba fukaku kizu tsuite shimau mono

Link to comment
Share on other sites

Link to post
Share on other sites

On 5.12.2016 at 7:37 PM, leonfagan71 said:

I've made a JS fiddle quickly.

http://jsfiddle.net/ew9o9b1q/

bear in mind that this is an example and has no security in it...

the JSON content is coming off of my webserver that has no cert so you need to load JSFIDDLE in plain HTTP for this to work.

My webserver is randomly picking the amount of notifications it shows.

it shows a random amount of notifications between 1 and 10 every time the page is loaded.

http://lhdns.cc.nf/cause_i_can/json.php

 

<a href="#" class="dropdown-toggle" data-toggle="dropdown">
              <i class="fa fa-bell-o"></i>
              <span class="label label-info">'.getNotAm($_SESSION['uid']).'</span>
            </a>

this displays the amount of notifications and it calls this function.

<?php

  function getNotAm($username) {

    $path = $_SERVER['DOCUMENT_ROOT'];
    include  $path.'/scripts/db_handler_script.php';

    if (isset($username)) {

    $unread = '0';
    $stmt = $conn->prepare("SELECT uid FROM notification WHERE uid=? AND status=?");
    if (!$stmt) {
      return ('---');
      exit();
    }
    $stmt->bind_param("ss", $username, $unread);

    $stmt->execute();
    if (!$stmt) {
      return('?');
      exit();
    } else {

      $result = $stmt->get_result();
      if (!$result) {
        $amount = '---';
      } else {
        $amount = mysqli_num_rows($result);
      }

      return ($amount);
      }
    }
  }

?>

each time I refresh the page it will display how many notifications I have and update if changed. so how can this be done?

And for those wo suggested websocket, I'm open for that too if I just get a basic how to do it, I tryed looking on the pages but I don't see how I can controll that it only displays what the user should see, etc how I can show Alex's notifications for Alex, and Jack's for Jack.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, Joveice said:

<a href="#" class="dropdown-toggle" data-toggle="dropdown">
              <i class="fa fa-bell-o"></i>
              <span class="label label-info">'.getNotAm($_SESSION['uid']).'</span>
            </a>

this displays the amount of notifications and it calls this function.


<?php

  function getNotAm($username) {

    $path = $_SERVER['DOCUMENT_ROOT'];
    include  $path.'/scripts/db_handler_script.php';

    if (isset($username)) {

    $unread = '0';
    $stmt = $conn->prepare("SELECT uid FROM notification WHERE uid=? AND status=?");
    if (!$stmt) {
      return ('---');
      exit();
    }
    $stmt->bind_param("ss", $username, $unread);

    $stmt->execute();
    if (!$stmt) {
      return('?');
      exit();
    } else {

      $result = $stmt->get_result();
      if (!$result) {
        $amount = '---';
      } else {
        $amount = mysqli_num_rows($result);
      }

      return ($amount);
      }
    }
  }

?>

each time I refresh the page it will display how many notifications I have and update if changed. so how can this be done?

And for those wo suggested websocket, I'm open for that too if I just get a basic how to do it, I tryed looking on the pages but I don't see how I can controll that it only displays what the user should see, etc how I can show Alex's notifications for Alex, and Jack's for Jack.

If you want to do it in PHP, you'd have to do a refresh for the interval you want.

 

If you want to do it in JavaScript using sockets and get requests, you can use my example from earlier. 

If you'd like, do you want me to include the script on my server?

 

you asked about checking the user, you also mentioned $_SESSION['uid'] could you not just include the session into the ajax PHP script?

then ensure that it's safe to use in a MySQL query?

 

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, leonfagan71 said:

If you want to do it in PHP, you'd have to do a refresh for the interval you want.

 

If you want to do it in JavaScript using sockets and get requests, you can use my example from earlier. 

If you'd like, do you want me to include the script on my server?

 

you asked about checking the user, you also mentioned $_SESSION['uid'] could you not just include the session into the ajax PHP script?

then ensure that it's safe to use in a MySQL query?

 

I guess I want it in javascript since I don't want to refresh my page. and If it's possible to both request and send data with that way then yea I would like to use the session.

And if you could do that I would be really happy :)

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

10 minutes ago, Joveice said:

I guess I want it in javascript since I don't want to refresh my page. and If it's possible to both request and send data with that way then yea I would like to use the session.

And if you could do that I would be really happy :)

Have a look at my example on jsfiddle.

 

This is my PHP file that has a random number of notifications, this was made quickly to support the JSFiddle that I made.

 

 

<?php header('Access-Control-Allow-Origin: *'); //for all to see - do not use.
$random=rand(0,10);
$array=[];
$array["notifications"]=[];
$i=0;
while ($i<$random){
	$array["notifications"][]=[
		"notification_content"=>"Hello world!",
		"notification_subject"=>"I am sparta",
		"notification_datetime"=>"2016-12-05 17:21:00",
	];
	$i++;
}
$array["count"]=$random;
$array["username"]="leonfagan71"; //this can be the session UID.

print json_encode($array);
?>

So you'd need to obviously make your own as mine doesn't use your database.

 

if you are currently using sessions, I'd suggest including start_session() at the top of this file and checking to see if the user id in the session has been set or not.

 

if it's been set then you can make sure it's safe before doing a similar type script on your server.

 

Please let me know if you have any issues.

 

Cheers,

Leon.

 

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, leonfagan71 said:

Have a look at my example on jsfiddle.

 

This is my PHP file that has a random number of notifications, this was made quickly to support the JSFiddle that I made.

 

 


<?php header('Access-Control-Allow-Origin: *'); //for all to see - do not use.
$random=rand(0,10);
$array=[];
$array["notifications"]=[];
$i=0;
while ($i<$random){
	$array["notifications"][]=[
		"notification_content"=>"Hello world!",
		"notification_subject"=>"I am sparta",
		"notification_datetime"=>"2016-12-05 17:21:00",
	];
	$i++;
}
$array["count"]=$random;
$array["username"]="leonfagan71"; //this can be the session UID.

print json_encode($array);
?>

So you'd need to obviously make your own as mine doesn't use your database.

 

if you are currently using sessions, I'd suggest including start_session() at the top of this file and checking to see if the user id in the session has been set or not.

 

if it's been set then you can make sure it's safe before doing a similar type script on your server.

 

Please let me know if you have any issues.

 

Cheers,

Leon.

 

and if my json returns {"amount":"7"} and only that how can I make it display that (this is for displaying total registered users on site)

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Joveice said:

and if my json returns {"amount":"7"} and only that how can I make it display that (this is for displaying total registered users on site)

Depends on what javascript code you have already...

<script>
  function loadNotificationContent(response){
	var jsonContent=$.parseJSON(response);
  $("#notifications").html(jsonContent["amount"]);
}
function getNotifications(){
	$.ajax({
    url: "http://lhdns.cc.nf/cause_i_can/json.php",
    cache: false,
    success: function(html){
      loadNotificationContent(html);
    }
  });
	setTimeout(function(){getNotifications();}, 30000);
}
getNotifications();
  
</script>

I'm sure you can work out what needs changing to suit your needs.

I've not changed the function names but have simplified the notificationsContent function.

Link to comment
Share on other sites

Link to post
Share on other sites

18 hours ago, leonfagan71 said:

Depends on what javascript code you have already...


<script>
  function loadNotificationContent(response){
	var jsonContent=$.parseJSON(response);
  $("#notifications").html(jsonContent["amount"]);
}
function getNotifications(){
	$.ajax({
    url: "http://lhdns.cc.nf/cause_i_can/json.php",
    cache: false,
    success: function(html){
      loadNotificationContent(html);
    }
  });
	setTimeout(function(){getNotifications();}, 30000);
}
getNotifications();
  
</script>

I'm sure you can work out what needs changing to suit your needs.

I've not changed the function names but have simplified the notificationsContent function.

Uncaught ReferenceError: $ is not defined
    at getRegAm (http://localhost/test.php:7:3)
    at http://localhost/test.php:16:1

?

<?php

    session_set_cookie_params(3600 * 24 * 7);
    session_start();

?>
<?php

  $path = $_SERVER['DOCUMENT_ROOT'];

  //scripts
  include_once($path.'/scripts/db_handler_script.php');

  //functions
  include_once($path.'/functions/notification_amount_function.php');

?>
<script>
  function loadRegAm(response){
  var jsonContent=$.parseJSON(response);
  $("#register").html(jsonContent["amount"]);
}
function getRegAm(){
  $.ajax({
    url: "http://localhost/scripts/autoupdate/live_registered_users_script.php",
    cache: false,
    success: function(html){
      loadRegAm(html);
    }
  });
  setTimeout(function(){getRegAm();}, 1000);
}
getRegAm();
  
</script>
<div id="register">
notifs
</div>

 

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Joveice said:

Uncaught ReferenceError: $ is not defined
    at getRegAm (http://localhost/test.php:7:3)
    at http://localhost/test.php:16:1

?


<?php

    session_set_cookie_params(3600 * 24 * 7);
    session_start();

?>
<?php

  $path = $_SERVER['DOCUMENT_ROOT'];

  //scripts
  include_once($path.'/scripts/db_handler_script.php');

  //functions
  include_once($path.'/functions/notification_amount_function.php');

?>
<script>
  function loadRegAm(response){
  var jsonContent=$.parseJSON(response);
  $("#register").html(jsonContent["amount"]);
}
function getRegAm(){
  $.ajax({
    url: "http://localhost/scripts/autoupdate/live_registered_users_script.php",
    cache: false,
    success: function(html){
      loadRegAm(html);
    }
  });
  setTimeout(function(){getRegAm();}, 1000);
}
getRegAm();
  
</script>
<div id="register">
notifs
</div>

 

Sorry, forgot to mention that this is done in JQuery.
most websites use it so I assumed that you'd already have it loaded.

If not, just include below, above the script tag :)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 

Link to comment
Share on other sites

Link to post
Share on other sites

20 minutes ago, leonfagan71 said:

Sorry, forgot to mention that this is done in JQuery.
most websites use it so I assumed that you'd already have it loaded.

If not, just include below, above the script tag :)


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 

Oh derp, yea I have it on my page just dident think over that I needed it in my test script too :P

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

23 minutes ago, leonfagan71 said:

Sorry, forgot to mention that this is done in JQuery.
most websites use it so I assumed that you'd already have it loaded.

If not, just include below, above the script tag :)


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

 

Ideal timeout? since each call is a database query.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, Joveice said:

Ideal timeout? since each call is a database query.

Depends what you want to update, 

30000 is 30 seconds, that's probably okay.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, leonfagan71 said:

Depends what you want to update, 

30000 is 30 seconds, that's probably okay.

for etc displaying registered users I'm fine by that, same for online people (which I also do not know how to do) but let's say, is 5-10 to fast for the notification part?

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×