Clearing notification onclick/toggle() - javascript

So I have a notifications system set up and it all works perfect except when I come to clearing the notification. Its clears ok when the div opens but it also clears if I refresh the page without the div been opened at all, I'm not wanting the notification to clear until the user has opened the notifications div. How would I go about doing this?
Any help or someone that could point me in the right direction will be greatly appreciated
Thank you
I have been using this line of code to clear the notification
<?php user_core::clear_notifications($user1_id); ?>
And this code is the OnClick toggle()
<div class="alert_header_item_container">
<a onclick="toggle('alert_dropdown');">
<div class="alert_header_item" id="alerts"></div>
<?
$sql = "SELECT * FROM notifications WHERE notification_targetuser=".$user1_id." AND notification_status = '1'" ;
$chant= mysqli_query($mysqli,$sql);
$num = mysqli_num_rows($chant);
if($num==1) {
echo '<div class="alert_header_item_new" id="alerts"></div>';
} else {
echo "";
}
?>
</a>

The issue you're having is this:
PHP does not load or execute Javascript. Here is an order of
execution:
The user requests data from your web server.
Your web server executes your PHP script, which outputs some HTML/Javascript.
The web server sends the HTML/Javascript to the user's browser.
The user's browser renders the HTML and executes the Javascript. So yes, the PHP will
finish executing before the Javascript is executed.
Basically your PHP is completed before you even toggle the onclick event.
What you really want to be doing is something like this:
Structure your HTML something like this.
<div class="alert_header_item_container">
<a id="read-notifications">
<div class="alert_header_item" id="alerts"></div>
</a>
</div>
Now we'd run an ajax request (when the document loads) to fetch the notifications
$(document).ready(function(){
$.ajax({
type: 'post',
url: 'notifications.php',
data: {id: user_id},
}).success(function(data){
$('alerts').html(data);
});
});
Which would call notifications.php where you'd run your php/sql to fetch the notifications:
<?php
$user1_id = $_POST['id']; // then sanitize as needed
$sql = "SELECT * FROM notifications WHERE notification_targetuser=" . $user1_id . " AND notification_status = '1'";
$chant = mysqli_query($mysqli, $sql);
$num = mysqli_num_rows($chant);
if ($num == 1) {
while($row = mysqli_fetch_assoc()){
// make notifications markup
}
echo MARKUP_FROM_ABOVE
}
?>
As for the onclick event, you'd do something like this (to a seperate php file that will update the notifications to set them to read (which is probably 0 ?)):
$(document).on('click', 'a#read-notifications', function(e) {
$.ajax({
type: 'post',
url: 'readnotifications.php',
data: {id: user_id},
}).success(function(data) {
// do what you need to do as notifications were read.
});
});
And on readnotifications.php you'd run an sql query that would update the notifications for $_POST['id'] (The user id) to 0 (read).

Related

Refresh php function in div without page reload?

I've made a more simple ping statues system for my servers.
Right now my PHP function does a simple fsockopen and show Green/Red echo if up/down.
This ping status is only shown when the site is loaded.
Question : Can I somehow refresh and execute the function again without the whole page reload?
I mean to have live status of servers changing if it goes down, without reloading the whole page.
<?php
function pingstate($host, $port) {
if (!$socket = #fsockopen($host, $port, $errno, $errstr, 0.1)){
echo "<p class='pingRed'><i class='fa fa-circle'></i></p>";
} else {
echo "<p class='pingGreen'><i class='fa fa-circle'></i></p>";
fclose($socket);
}
}
?>
Example of output I use on other page than the function.
This part works great but I have to "reload" the page everytime I want new status of the ping.
$host = $row['host'];
$port = 80;
echo "<tr>
<td>" .$row['eq']."</td>
<td>".$row['ChargePoint']."</td>
<td>".$row['ip_addres']."</td>
<td>".$row['host']."</td>
<td><i class='fa fa-dashboard'></i></td>
<td><a href='http://".$row['host']."/' target='_blank'><i class='fa fa-gear'></i></a></td>
<td>";
echo pingstate($host, $port);
echo "</td></tr>";
I was thinking of maybe JavaScript that reloads the table row?
How can this be done, I googled but cannot find for reload functions..
Please help me with explanation, I really want to learn.
Thank you!
First things first: its real bad coding style to use PHP to echo html. You should avoid it if possible.
My structure would look like this:
create a file called server_check.php and use your checking code inside like this:
if (!$socket = #fsockopen($_GET["HOST"], $_GET["PORT"], $errno, $errstr, 0.1)){
echo json_encode("offline");
die;
} else {
echo json_encode("online");
fclose($socket);
die; }
echo json_encode("no ping possible");
Next step is to create a html file with the following content. I'm using jQuery for simplifying your problem. You may use vanilla javascript if you prefer that.
let server_list = {
"example.com": 111,
"example1.com": 111
};
function checkServer() {
for (const [key, value] of Object.entries(object)) {
$.ajax({
url: "server_check.php",
data: {
HOST: key,
PORT: value
}
}).done(function(data) {
$('#'+key).text(data);
});
}
}
setInterval(checkServer, 10000); //Checks server each 10 secs
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> Info about Server EXAMPLE.COM Server is
<p id="example.com">NOT CHECKED</p>
Server EXAMPLE1.COM Server is
<p id="example1.com">NOT CHECKED</p>
EDIT: Please be aware of several security issues and non existent error handling. Please read on several topics (GET/POST/HTTP requests) and ajax in general before using this in a productive environment. If you have further questions feel free to ask them right away.

Trying to make php login work with Phonegap

I understand that for a login / register system to work within Phonegap, you have to use aJax with your php. I've got a sucessful php login and register page working but I'm unsure where to begin with jQuery / aJax a.k.a where I'm meant to put it, and what exactly I should be putting in. I was wondering if someone would know how to point me into the right direction.
jQuery
jQuery is a framework built on Javascript. Javascript is a client-side (browser) language . It runs on your device, unlike PHP that gets executed on the server.
You need to include jQuery in the HTML of your login page using script tags:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
jQuery provides a way to target any html element within your document and perform certain functions on that element. You specify what element by using the following syntax:
$(element).doSomething();
You can select classes or IDs:
<p id="myparagraph">A paragraph of text</p>
<p class="myparagraphclass">A paragraph of text</p>
$('#myparagraph').doSomething();
$('.myparagraphclass').doSomething();
AJAX
AJAX is a method introduced with Javascript that allows a page to request another url along with the result of that request. You will need to use AJAX login with Cordova/Phonegap because the "app" you're building is based on Javascript.
Thankfully, jQuery provides some really nice and easy to use AJAX methods.
Putting it together
I notice from a previous question that you have already created a PHP script that checks the login credentials are correct. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/access/login.php on line 15
I have edited slightly the code within that question (/access/login.php):
require_once($_SERVER['DOCUMENT_ROOT'] . "/html5up-aerial/access/functions.php");
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username&&$password) {
session_start();
require_once($_SERVER['DOCUMENT ROOT'] . "db_connect.php");
mysqli_select_db($db_server, $db_database) or
die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
*if($row = mysqli_fetch_array($result)){*
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
//header('Location: home.php'); // Have commented this out
$message = "YOU ARE NOW LOGGED IN!"; // <- ADDED THIS
}else{
$message = "<h1>Incorrect password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='index.php'>try again</a>";
}
mysqli_free_result($result);
require_once("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
//header/footer only required if submitting to a seperate page
echo $message; // ADDED THIS
die(); // ADDED THIS
This will be the PHP script that AJAX requests.
Now we create the HTML document with a login form and include jQuery and write our ajax code:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form class="login-form" method="post">
Username: <input name="username" /><br />
Password: <input name="password" type="password" /><br />
<input type="submit" value="Login" />
</form>
<script>
$('.login-form').on('submit', function(e) { // Listen for submit
e.preventDefault(); // Don't actually submit the form
var data = $(this); // Put the form in a variable
$.ajax({
type: "POST",
url: '/access/login.php',
data: $(data).serialize(), // Make form data into correct format
success: function(response) {
alert(response); // Alert with the response from /access/login.php
}
});
});
</script>
To debug this code you will need to use Chrome development toolbar or Firefox Firebug. Hope this helps.

PHP session not persistent with AJAX

I'm working on making a website (developing locally) that requires a login for users; I've used php-login.net framework as my starting point and have my code talking to MySQL and creating sessions just fine.
I've gone through most every SO question regarding php sessions and ajax; but I still can't get my code to work how I want.
Now, I'm using ajax to call some other php scripts after the user successfully logs in, however it's not working properly. In firefox, with all the cookies, history, etc cleared, it looks like the session variables aren't maintained with the ajax call. However, if I log-out and then log back in, the session variables seem to be passed properly across ajax.
For example:
In my logged_in.php script, I'm using ajax to call another script: view_samples.php.
logged_in.php
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButtons.js
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
url: "view_samples.php",
cache: false,
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
When I log in with a browser that hasn't logged in before, I see it sets a session ID X; however when the button is pressed and the ajax call is made, I see a new session ID Y. I then log-out and log back in and see that my session ID is Y (before ajax) and that my session ID is Y when I click the button (after ajax).
I've also noticed that if I keep logging-in & out without pressing the view samples button, a new session id generated each time. However, as soon as I press the button, a whole new session id is created which seems to always be the one that is set if I log-out and then back in.
What am I missing? What's the proper way to go about ensuring the first session that is created is maintained throughout ajax calls? Should I POST the session id to the called script?
This is how I solved things (as Freaktor's comment above didn't resolve the issue) - I'm manually passing the session ID through AJAX and then setting it in the new PHP script. I'm wondering if anyone could comment on the security of this (as I'm not entirely sure how this all works)?
This and this post were helpful.
logged_in.php
<script>var session_id = '<?php echo session_id();?>';</script> <!-- store our session ID so that we can pass it through ajax -->
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButton.js
var data = {func:'getData1',session_id:session_id}; // manually send the session ID through ajax
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
type: "POST",
data: data,
url: "view_samples.php",
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_id($_POST['session_id']); // get the session ID sent by AJAX and set it
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>

need javascript or jquery function to wrap php code (window.setInterval bootstrap list group)

Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics

Link to a page and trigger ajax via the same button

I'm trying to make a div button which triggers ajax and links to a page which the ajax is posting data to. I have the ajax working on click, but can't seem to get the link to work at all with it, all the ways I've tried to get the link working do nothing.
I have a div button:
<div class="cman shadow1" id="search_button" value="carSearch"/>
Start Search
</div>
Which triggers:
function carSearch()
{
$.ajax({
type: "POST",
url: 'searchpost.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val());
}
});
}
Edit:
Feel I should mention that the page I wish to link to is atm:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$mpg = (int)($_POST["mpg"]);
header("Location: home.php");
exit;
}
?>
I wish to use this to gather all of the search fields the user enters to then load the search results page. The above code for it is just for testing right now.
I mention this as user #Doge suggested doing document.location.href = "searchpost.php" in the success handler of the ajax, this did cause the page to change but the page didn't run the isset and the redirect, so the js variable wasn't posted, or it was but this instance of the page didn't get it.
The isset and redirect do work as using the XHR Network tab on my page the page it is to redirect to appears.
If you must do this via js then create a hidden form, populate it and submit it:
html:
<form method="post" id="hiddenform" action="searchpost.php">
<input type="hidden" name="mpg" id="mpg"/>
</form>
js:
function carSearch()
{
$('#mpg').val(yourjsvariable);
$('#hiddenform').submit();
}

Categories