Updating $_SESSION variables using Ajax - php

On my main page I assign four different $_SESSION variables as follows:-
<p class="p-wht space left">Working: <? echo $_SESSION['Working'] ?></p>
<p class="p-wht green space left">Clear: <? echo $_SESSION['Clear'] ?></p>
<p class="p-wht red space left">Busy: <? echo $_SESSION['Busy'] ?></p>
<p class="p-wht cyan space left">STC: <? echo $_SESSION['STC'] ?></p>
These are set when the page loads:-
include('status.controller.php');
and they are set as:
$_SESSION['Working'] = $status['Working'];
$_SESSION['Clear'] = $status['Clear'];
$_SESSION['Busy'] = $status['Busy'];
$_SESSION['STC'] = $status['STC'];
They update when the page is refreshed or first loaded, but when I am trying to update them using AJAX the values don't seem to be changing.
I have tried:-
$(function(){
setInterval(function(){
$.ajax({
url:'scripts/php/status.controller.php',
success:function(data){
if(data == "scripts/php/status.controller.php"){
}else{
alert(data);
//location.reload();
}
}
});
},4000);
});
but this doesn't seem to update the values. It only updates the values when the page is completely reloaded, including location.reload(); which I don't want to use.
Any ideas?
ADDED; contents of status.controller.php file; here is the contents of this file; nathandasilva.co.uk/status.controller.txt

Can you tell me, what is the output of scripts/php/status.controller.php page. If the page will send html as output, then you should just replace the content, example:
<div id="content">
<p class="p-wht space left">Working: <? echo $_SESSION['Working'] ?></p>
</div>
<script>
$(function() {
setInterval(function(){
$.ajax({
url:'scripts/php/status.controller.php',
success:function(data) {
$("#content").html(data);
}
});
},4000);
});
</script>

Related

How to make only two div clickable among multiple divs and send their content to php file

I have this php file which is fetch data from my database and place it into divs. this div created by while loop I want tow div only to be select then send the content to php file using Ajax.
The code execute with no problem but there is no result!!
Any help advance and I completely lost of mind !!!
while($row=mysqli_fetch_array($result)){
$so=$row[0];
$s=$row[1];
$m=$row[2];
$a=$row[3];
$b=$row[5];
$c=$row[8];
?>
<body>
<div id="all"> //start all
<div class="r"> //start r
<div id="e"><?php echo"{$s}"; ?></div>
<div id="b"><?php echo"{$m}"; ?></div>
<div id="a"><?php echo"{$a}"; ?></div>
<div id="b"><?php echo"{$b}"; ?></div>
</div> //end r
</div> //end all
<?php
} //end while
?>
<div id="show"></div>
script code
$(document).ready(function(){
$(".r").click(function(){
$data = $(this).text();
alert($data); //it work well
$.ajax({
url: "view.php",
type: "post",
data: {
you: $data
},
success:function(response){
$('#show').html(response);
}
});
});
});
view.php
<?php
if(isset($_post['you'])){
printf("ok"); //just to check
}
?>
First of all
IDs on a page should be unique
Now coming to your code, maintain a global variable to have select count and call the below function to allow selection of maximum 2 divs
var selectCount = 0;
$('.r div').click(function() {
if(!$(this).hasClass('active') && selectCount < 2) {
$(this).addClass('active');
selectCount++;
}
else if($(this).hasClass('active')) {
$(this).removeClass('active');
selectCount--;
}
else {
alert("ony 2 allowed");
}
});
To send the data to your call you can
$('button').click(function() {
var result = [];
$('.active').each(function(val){
result.push(val);
});
});
You may change the data format accordingly.

ajax php GET/POST without refresh

I need to execute the following code, without refreshing the page... this code already includes ajax but where am I going wrong with getting it to execute without refreshing the page....? the .vote class is attatched to an anchor in my index.php file, and I need this all to still work when the anchor is clicked if possible. Re-coding this to perform on a button click would not be ideal.
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html){
parent.html(html);
}
});
}
});
here is the html from my index.php
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $totalvotes1; ?><br />
</div>
<div id="message">
<?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<?php echo $totalvotes2; ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>
You need to either enclose your code with $(document).ready(function() {});, or stick your code at the end of the <body> tag. Personally, instead of making the browser parse synchronous javascript before the DOM has loaded (in the <head> section), I stick it near the end. This is also what Bootstrap recommends.
Without a DOM loaded, there are no elements created for jQuery to register Events with, and so your code literally sits there doing nothing after being parsed.
Aside from that, the .click() function is executed on click. It doesn't matter what element it's bound to. If it's clickable, it's executable.
Also to answer your question properly: <a href=""> will refresh the page. You want to use
<a href="#">. This, however, will make you jump to the top of the page. You could also define a <label> and use #labelname instead to avoid this. Or just don't use href at all. It's not needed.
Also, a little trick for echoing variables into HTML is to use <?= $var ?>

Loading Content using Ajax with PHP Include

I have a PHP page which has a div, the div has a PHP includes which includes this file:
<?php
include('mySql.php');
include('Classes.php');
$targetPage = "blogOutput.php";
$noOfPosts = getNumberOfPosts();
$adjacents = 3;
?>
<link rel="stylesheet" type="text/css" href="Styles/Miniblog.css" />
<script src="Scripts/jQuery.js"></script>
<script type="text/javascript">
var page = 1;
$(".Button").click(onClick());
$(document).ready(onClick());
function onClick() {
alert('called');
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
}
</script>
<div class="PostTitle">
<h2>What's New!?</h2>
</div>
<div id="posts">
</div>
<a class="BlogButton" href="">Next</a>
I need the function "onclick" to be called without refreshing the page and resetting the "page" variable in javascript. So far, all I've been able to do is make it run the script once. I think that's wrong too, because it's not loading any content. Here's the page:
<?php
echo "I'm here!";
if (isset($_POST['offset'])) {
$offset = $_POST['offset'];
$posts = getPosts($offset);
}
?>
<div class="BlogPost">
<h3><?php echo $posts[0]->Title; ?></h3>
<p><?php echo $posts[0]->Body; ?></p>
<p class="Date"><?php echo $posts[0]->Date; ?></p>
</div>
<div id="divider"></div>
<div class="BlogPost">
<h3><?php echo $posts[1]->Title; ?></h3>
<p><?php echo $posts[1]->Body; ?></p>
<p class="Date"><?php echo $posts[1]->Date; ?></p>
</div>
So, to clarify: I'm not sure why my ajax call isn't working, and I don't know how to load just the div content and not refresh the entire page. Thanks!
You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.
<script type="text/javascript">
var page = 1;
$(document).on('click','.BlogButton',function(e){
// stop page from reloading
e.preventDefault();
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
</script>
Don't call the function in the click method parameter. You have to put the reference to the handler function.
var handler = function onClick () {...}
$("whatever").click(handler);
Change your code to
var page = 1;
$(document).ready(function(){
$(".Button").click(onClick);
onClick();
};
Use this instead of your code
var page = 1;
$(document).on('click','.Button',function(){
$("#posts").load("miniBlog.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Error!: ";
alert(msg);
}
});
page++;
});
Content dose not look too huge.Can't you just hide div (with content already present in it)& show it onclick.

change the content of div after submitting data to mysql

i am new to ajax . i want to submit a data with the help of ajax and then get the new data replacing the old one in the same div as of which the old data was .
here is the jquery for sliding tab
$(document).ready(function() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
});
ajax
function addhubs()
{
var group =$('#customhubs').val();
var user=$('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val='+group+'&& loguser='+user,
success: function(html){
}
});
}
the div i want to replace data
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php $sql=mysql_query("select * from groups");
while($ab=mysql_fetch_array($sql))
{
$gpID[]=$ab['group_id'];
$gp=$ab['group_id'];
$gpName=$ab['group_name'];
?>
<li><?php echo $gpName;?></li>
<?php
}
?> </ul>
</div> <!-- /.st_slide_container -->
</div> <!-- /.st_tabs_container -->
and the mfrnds.php of the ajax call file contains query to update the new data.
$user=$_GET['loguser'];
$group=$_GET['val'];
$sql=mysql_query("insert into groups (group_name) values ('$group')");
how can i update the div in the above . plz help me .m stuck badly luking for solution from 4 days. thanks
Note that in your addhubs function you should only add one & in your url and concatenate everything without spaces in between such as below.
When the ajax call has finished it returns the contents of the page you requested (mfrnds.php) in the html variable. So you can simply select the div you want and enter the html as you can see below. So here we go...:
Your Page
<html>
<body>
<script>
$(document).ready(function() {
setupTabs();
});
function setupTabs() {
// Vertical Sliding Tabs
$('div#st_vertical').slideTabs({
// Options
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
orientation: 'vertical',
tabsAnimTime: 300
});
}
function addhubs() {
var group = $('#customhubs').val();
var user = $('#loginuser').val();
$.ajax({
type:"GET",
url: 'mfrnds.php?val=' + group + '&loguser=' + user,
success: function(html) {
//Get div and display the data in there
$('div.st_slide_container).html(html);
//As your slide effect is gone after you updated this HTML, redo your slide effect:
setupTabs();
}
});
}
</script>
<!-- Vertical div -->
<div id="st_vertical" class="st_vertical">
<div class="st_tabs_container">
<div class="st_slide_container">
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
</div> <!-- /st_slide_container -->
</div> <!-- /st_tabs_container -->
</div> <!-- /st_vertical -->
</body>
</html>
So in your mfrnds.php you should have a PHP script that uses the val and loguser GET variables and updates the database. After the database has been updated you should return the updated HTML like the following:
*mfrnds.php
<?php
$user = $_GET['loguser'];
$group = $_GET['val'];
$sql = mysql_query("insert into groups (group_name) values ('$group')"); ?>
<ul class="st_tabs">
<?php
$sql = mysql_query("select * from groups");
while($ab = mysql_fetch_assoc($sql)) {
$gp = $ab['group_id'];
$gpName = $ab['group_name']; ?>
<li>
<a href="#stv_content_<?=$gp?>" rel="v_tab_<?=$gp?>" class="st_tab ">
<?php echo $gpName;?>
</a>
</li>
<?php
}
?>
</ul>
Note though that this code is basically meant as an example, I don't know what you want to do exactly in mfrnds.php etc, but I hope this gives you a good idea!
It looks like you are almost there.
In your mfrnds.php file add a line to grab the updated rows
use:
PSEUDOCODE
"SELECT * FROM groups"
for each row in groups
echo "<div> groups.name groups.category </div"
and then in your callback function
success: function(html){
$('.st_tabs').html(html); //replace the html of the sttabs div with the html echoed out from mfrnds.php
}

Jquery, ajax and problem with load

This is the HTML part:
div id="messages">
<div class="messages">
<?php if(isset ($unread)) { ?>
<p>You have <?php echo $unread?> unread messages.</p>
<?php } ?>
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
<?php } ?>
<?php } ?><!-------- end of if $message-------->
</div><!------ end of div .messages--------->
</div><!------ end of div #messages--------->
and JQ:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>");
});
});
}
});
return false;
});
Code is working, but when it comes to the load nothing is being shown. I did
load("<?php echo site_url('messages/show') ?>", function() {
alert('Load was performed.');
});
and there was an alert, and when I look page source I can see that the content has been changed, but it is not displayed.
When you view the source of a page that has been loaded via AJAX, it will never update. You will need to inspect the DOM in order to see what has changed.
The reason is because the content is not actually on the page and is being dynamically added to the page.

Categories