Showing notification with AJAX - ajax

I have a navbar on my users' panel. A part of the navbar indicates if the user has a new unread message. In this case a badge will appear next to an icon. I've simplified the codes here to make them easier to understand and read.
So this is the simplified HTML code:
<div class="btn-group msg-box">
<i class="fa fa-envelope"></i>
// this is the default state, no badge is shown
</div>
Here is the AJAX request which calls a custom function every 10 seconds:
<script type='text/javascript'>
$(document).ready(function(){
setInterval(checkMsg,10000);
});
function checkMsg(){
$.get('ajax.php',{user_id : <?php echo $user_id; ?>},function(data){
$('.msg-box').html(data);
});
}
</script>
And this is the ajax.php file content:
if(isset($_GET['user_id']){
// a few lines of code here to check if that particular user has any unread message.
// In such case a variable name $newMessage is set to 1. Now ... :
if($newMessage>0){
$data='
<i class="fa fa-envelope"></i>
<span class="badge"><i class="fa fa-info"></i></span>
';
}else{
$data='
<i class="fa fa-envelope"></i>
';
}
echo $data;
}
First of all, I know the way I've written this AJAX request is very rookie, but it works fine anyway, up to one point!
In case the user has a new message, and if they stay on a page, the code runs perfectly and shows the badge. But when the user refreshes the page or goes to another page, even-though they have a new message, that default state is shown again where there's no badge. And I know it's of course because I have specified a default state via HTML codes.
I need to know how I can keep the result of the AJAX request regardless of how many times the user refreshes the page or goes to another page.
UPDATE
I tried storing the query result in a SESSION in my ajax.php file. So instead of $data I wrote $_SESSION['data'].
Back on my HTML I made the following change:
<div class="btn-group msg-box">
<?php
if(!isset($_SESSION['data'])){
?>
<i class="fa fa-envelope"></i>
<?php
}else{
echo $_SESSION['data'];
}
?>
</div>
I made this change because I considered the fact that SESSIONS, by definition, are created and accessed globally within the domain. So once it's set, it can be checked and used on all other pages.
So that only if that SESSION isn't set, the default state should be displayed. But that as well doesn't seem to have my desired result. Still the same thing happens.

Ok, answering my own question now. :)
My UPDATE seemed to be a good idea which I tried.
The problem there was that I had written session_start(); on my main PHP file which was included in all other PHP files of the project.
So I basically thought that when the ajax.php file is called, there's no need to write session_start(); again. Because ajax.php was called inside a PHP file that had session_start(); in it already. So, I was wrong!
Adding session_start(); to the beginning of my code in ajax.php simply fixed the issue.

Related

Infinite go back loop

I m building an app with a procedure to deposit folder so the user must browse different pages like this:
firstPage->secondPage->thirdPage...
So I used this:
<input type="button" value="Go Back" class="btn btn-primary">
But when I'm in the third page and go back it does:
thirdPage->secondPage->thirdPage...
With an infinite loop
How can I fix this?
Thank
Just using {{ URL::previous() }} won't solve your problem, because imagine you're at second page then goes to third, then come back to second: At this moment, the previous page is the third one, that's why this is happening. So if you want to fix this, you'll have to know to where each page should go and place that logic there. So if page2 must go back to page1, you'll have to do something like this:
#if( Request::is('secondPage') )
<script type="text/javascript">
window.location = "{ url('/firstPage') }";
</script>
#else
.....
#endif

How do I pass a variable to a controller function from the view in CodeIgniter?

I have a user controller with an agentexport function, which is supposed to download an excell spreadsheet. Below is the function:
function agentexport($agentName) {
if($this->isAdmin() == TRUE) {
$this->loadThis();
}
else {
$this->excel->setActiveSheetIndex(0);
// Gets all the data using agent name
$data = $this->excel_model->getdatabyname($agentname);
//print_r($data);
//die;
$this->excel->stream('crosstown.xls', $data);
}
}
In my views I am trying to execute the above function with the following button:
<a class="btn btn-sm btn-info" href="<?php echo base_url().'agentexport/'.$record->agentName; ?>" title="Download Sheet><i class="fa fa-pencil"></i>Download Sheet</a>
The above button is meant to download the spreadsheet right away.
The url is defined in my routes as :
$route['agentexport'] = "user/agentexport";
Did I define my route the right way ? When I click on the route I get the following url
http://www.XXXXX.com/John%20Grisham.
As you can see, the name is appended at the end of the url but the page shows a 404. What am I doing wrong ?
Personal opinion here, but I don't think there's any strong reason to use a route. If nothing else, the following will be a good experiment to see if the $route definition is the problem.
Delete the $route you have been using for 'agentexport'.
Change the link to
<a class="btn btn-sm btn-info" href="<?= base_url('user/agentexport/'.$record->agentName); ?>" title="Download Sheet"><i class="fa fa-pencil"></i>Download Sheet</a>
To test that the link works and is passing the value, use the following version of agentexport
public function agentexport($agentName)
{
echo $agentName;
//or alternately
//var_dump($agentName);
}
It is assumed that you verified $agentName is a usable value before you used it in the link. If the above shows you a value, then you know the $route was the problem.
You can experiment to find a $route, but $route['agentexport/(:any)'] = 'user/agentexport/$1'; should work. If you're going to switch back to using a route don't forget to revert the link code. I'd write it like this, where the URI is passed as an argument to base_url.
<a class="btn btn-sm btn-info" href="<?= base_url('agentexport/'.$record->agentName); ?>" title="Download Sheet"><i class="fa fa-pencil"></i>Download Sheet</a>
If you find a route that works - and using a route is what you really, really want - then restore the code in agentexport to what you actually need. But again, I don't see any strong reason to obfuscate the link's URL.
If, from the view, you're pointing to /controller_name/method/agent_name (which is basically what you're doing after the route "translation", all you need to do is pick the agent name from the URI using the URL helper (remember to load it beforehand)
$user_id = $this->uri->segment(3);
The above will take whatever is in the third segment of the URI (agent_name in my example) and assign it to the $user_id variable.
Remember that whatever is possible to be manipulated by the user cannot be trusted, so you need to sanitize $user_id and make sure that the user requesting the file is allowed to access it

Onclick Magento PHP

I need to click on a button and change an order state. So far I've done this:
<?php $_order = $this->getOrder() ?>
<div class="buttons-set">
<p class="btn">Button</p>
</div>
In my php I have:
public function saveState($order)
{
return $order->setState(Mage_Sales_Model_Order::STATE_NEW, true);
}
The problem is that every time the phtml loads it executes the saveState function, changing the order state everytime, dont know why. I need to execute the saveState function just where the button is clicked. Please help me with this one, i'm really stuck!
Thanks
Button doesn't link to a saveState() method. It just executes the saveState() method immediately, and links to the return value of saveState(), in this case I'm guessing that would just be the string representation of a sales/order object.
What you need to do is create a Controller whose action you can link to, via something like
<a href="<?php
echo Mage::getUrl('YourModule/YourController/YourAction')
?>">Button</a>
Please note as well that having an "action" in a simple link is generally considered bad practice: it is not RESTful.

Getting instant ajax responce

I think there is a way to do this in ajax. But if you have a better way please let me know.
I have this code:
$interactionBox= '<input type="button" value="Pending Friend Requests('.$num_rows.')" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'friend_requests\');"/>';
This code opens up a togle box where user can accept friends if there is a pending request.
So if button looks like this:
Pending Friend Request(1)
And user accepts that request user has to refresh the page for this to show as:
Pending Friend Request(0)
Is there a way to do this without refreshing the page using ajax or any other way?
Here is HTML for above code:
<div class="interactContainers" id="add_friend">
<div align="right">cancel </div>
Add <?php echo $username; ?> as a friend?
Yes
You can just get the value between brackets with JavaScript and then reduce by 1,
You can get that value (if it isn't a variable get via regexpresion:
var button = document.getElementById('buttonid'); // fill in the id
button.value = "Pending Friend Requests("+ (parseInt(button.value.match(/\d{1,10}/)) - 1) + ')';
just excute that after each accept (or not-accept)
note you should just use the function in onclick, it's not a link so it will only excute the javacript bit: so no onmousedown just onclick="javascript:toggleInteractContainers(\'friend_requests\');"
look ma: no jQuery!

PHP Sessions Var Not Storing... Possible php.ini issues?

I'm trying to store information on a form by using sessions in case the validation returns false, then the user doesn't have to refill the form. This how I'm doing this:
PAGE A:
<?
session_start();
$Fname = $_SESSION['FirstName'];
?>
<html>
<input type="text" id="First" value="<? if($Fname){echo $Fname;}?>">
</html>
PAGE B:
<?
$Fname = $_POST['First'];
session_start();
$_SESSION['FirstName'] = $Fname;
//validation is not good then
header('Location: PageA.php');
?>
The issue is that when sent back to page A, nothing is showing up in the inputs, but randomly it will show up or, I'll refresh and it might show up. For most part its just not working and what I don't understand it kind of just started happening when I made a modification of removing one of the session vars and replacing it with a cookie because of other reasons, but decided not to go that route. Still I don't see what I could have done to start causing this issue. Any ideas? I'm thinking its something with the php.ini file because i have a separate form with the same setup and I never touched it, and now its not working when it was the last time i checked.
UPDATE
I just tried the form, I submitted it incorrectly on purpose to trigger the validation and it sent me back with blank inputs as I already mentioned. I clicked on another page and then came back to the form and the inputs appeared. It seems as if its storing but just not being read immediately? Don't know if this helps.
On Page B session_start() should be the first command on the page. I always keep this at the top just to be sure
You do not need SESSION at all ...
PAGE A:
<?
$Fname = isset($_POST['First']) ? $_POST['FirstName'] : '';
?>
<html>
<form method='post' action='PageB.php'>
<input type="text" id="First" value="<? if($Fname){echo $Fname;}?>"/>
</form>
</html>
PAGE B:
<?
//validation is not good then
include 'PageA.php';
exit;
?>
Not sure if it is a typo, but in your input tag you don't have the "name" attribute specified, which would mean an empty $_POST array when you go to page B.
It's difficult (for me at least) to help you without further details, but here are my thoughts:
From the PHP manual: "Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant. "
One solution found in other forums: call session_write_close() before the header redirection: external link
Apparently, header() can sometimes make the redirection BEFORE the session cookie is written. That could explain why sometimes it works and other times it doesn't. But, as I said, not sure that this applies to your code.
I got it working by filling in the things you left out in your example; does it work for you?
PageA.php
note addition of <form action="PageB.php" method="POST"> and change of id="First" to name="First"
<?
session_start();
$Fname = $_SESSION['FirstName'];
?>
<html>
<form action="PageB.php" method="POST">
<input type="text" name="First" value="<? if($Fname){echo $Fname;}?>">
</form>
</html>
PageB.php
(unchanged)
<?
$Fname = $_POST['First'];
session_start();
$_SESSION['FirstName'] = $Fname;
//validation is not good then
header('Location: PageA.php');
?>

Resources