I know ajax is probably the best method to do this.
So, i have this php file which returns a count:
<?php
include('globals.php');
$query = mysqli_query($con, "SELECT COUNT(*) as total FROM solicitacoes WHERE visualizada = 0");
$resultado = mysqli_fetch_array ($query);
$sem_visualizar = $resultado['total'];
return $sem_visualizar;
And i have this on my main page:
<?php
if($_SESSION['funcao_corrente']=="adm" || $_SESSION['funcao_corrente']=="analista"){
echo '<label onclick="mudaIframe();" id="visu" ';
if ($sem_visualizar == 0)
echo 'style="background-color: darkgray; color: black;"';
else if ($sem_visualizar<=5)
echo 'style="background-color: green;"';
else if ($sem_visualizar>5 && $sem_visualizar <= 15)
echo 'style="background-color: orangered;"';
else if ($sem_visualizar>15)
echo 'style="background-color: red;"';
echo '>'.$sem_visualizar.'</label>';
}
?>
Basically it just changes color based on value, but the thing is:
I want it to auto refresh it's own value via the PHP file which returns count, but I have absolutely no idea how can i do this.
I found this code in another answer, but it's not working.
<script>
function get_msg_count(){
$.ajax ({
data: {}, // not really needed
type: 'POST',
url: 'contar_sem_visualizar.php', // page to return your msg count
success: function(response)
{
$('#visu').html(response);
}
}
}); // End $.ajax
} // End Function
// and on DOM ready
$(function(){
// check for new messages every 3 seconds(3000ms)
setInterval(get_msg_count(), 3000)
});
</script>
You can just use $.load to achieve that:
HTML
<span id="count"></span>
jQuery
$("#count").load("contar_sem_visualizar.php");
You need an element to set the count and use jQuery to put the answer in there. The return from your PHP will be retrieved from the jQuery request and ever after a set interval the client's browser will send a request asking for this value, which will be added again to the counter.
You could do that:
function get_count(){
while()
{
$("#counter").load("contar_sem_visualizar.php");
setInterval(3000);
}
}
get_count();
Related
I'm trying to access each element stored as a Base64 image/blob in a JSON array constructed from a MySQL query.
The idea is to click a button that goes through each element and displays the image.
I have gotten it to display the first image however when i click again, the next image doesn't show.
Any help will be much appreciated.
AJAX:
$(function () {
$('#getimg1').on('click', function () {
$.ajax({
type:'GET',
dataType: 'json',
url: 'http://testing/api/getimg',
success:function(getinfo){
$.each(getinfo, function(i, displayimg){
$('#HTMLBox').prop('src','data:image/png;base64,' + displayimg.XXX ---- //Here I'm suspecting something?);
});
}
});
});
});
PHP:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
echo json_encode($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I'm using just 2 images to test this.
Because the ajax call you make will return all of the image records, I think it would be more efficient to store that data in a variable and then just rotate through the images rather than making call to your php code with each click. Here's what I would suggest, if you're using just jQuery:
var images = [],
index = 0,
count = 0,
max = 0;
$.getJSON("http://testing/api/getimg", function(data) {
images = data;
count = images.length;
max = count - 1;
});
$('#getimg1').on('click', function() {
if (count === 0) {
return;
}
if (index === max) {
index = 0;
} else {
index++;
}
$('#HTMLBox').attr('src', 'data:image/png;base64,' + images[index]);
});
I must admit I didn't test it, but I believe it should work - if you could try and see how you get on.
So, if you wanted to do something really dirty, you could track how many images you've loaded via a hidden input. You can increment that upon your ajax success. Then, what you can do is pass to your PHP via your AJAX that value, and run something like:
SELECT * FROM images LIMIT 1 OFFSET $images_already_fetched
By passing an OFFSET declaration, you're telling it to skip that many rows.
Right now, every time a user logs in, all the posts made by that user will turn green, while all the offline users' posts are grey.
I want to add a link to a javascript function for when the div is green, and a different link for when it's grey. I did this in php no problem but I want it to work realtime just like the color change without a page refresh.
The html
<div class="main_ads status" id="user'.$user_id.'">post</div>
status.php
header('Content-Type: application/json');
$array = array();
$res = mysql_query("SELECT * FROM `users` WHERE `status` = 1");
if(mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$array[] = 'user'.$row['user_id']; // this adds each online user id to the array
}
}
echo json_encode($array);
ajax code
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.length > 0){ // if at least 1 is online
$('.status').each(function(){ // loop through each of the user posts
var userid = $(this).attr('id'); // get the user#
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: '#40A547'});
} else{ // if not, set to offline
$(this).css({background: '#7f8c8d'});
}
});
} else { // if no one is online, set all to offline
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 2000);
});
I tried to think of a way to do this and thought to assign a variable with a html tag that will be different for online and offline but wasn't sure how to call that variable from the ajax code into html.
All help is much appreciated!
You could make use of the wrapInner() property of jQuery. This could enclose the text place inside your div into <a></a> tags such as:
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: '#40A547'});
//for the online users, you could fill in the javascript function
$(this).wrapInner('');
} else{ // if not, set to offline
$(this).css({background: '#7f8c8d'});
//over here write the link for offline users
$(this).wrapInner("<a href='www.google.com'></a>");
}
Fiddle
Do not add inline styles, use css classes.
In case the request takes longer than 2 seconds, abort it!
I suggest not using id's, mabye data-user or .user# as class
HTML
<div class="main_ads status" id="user1">post1</div>
...
<div class="main_ads status" id="user10">post10</div>
CSS
.online{
background:red;
padding:3px;
}
JQUERY
var global_ajax_request = null;
$(document).ready(function() {
setInterval(function(){
if (global_ajax_request){
global_ajax_request.abort();
}
global_ajax_request = $.ajax({
url: 'ajax.php',
dataType: "json",
type: 'GET',
success: function(data) {
$('.status').removeClass('online');
for(var i in data){
$('#'+data[i]).addClass('online');
}
}
});
}, 2000);
});
$('.status').on('click',function(e){
e.preventDefault();
if ($(this).hasClass('online')){
alert('function for ONLINE');
}else{
alert('function for OFFLINE');
}
});
Explanations:
global_ajax_request holds the reference to a request. Just before launching a new one, kill the old one. (!) This will make the browser not listen for a response, but the server will continue to work.
Each time you get a response, clear the online class and add it only to the returned userId's. (This should be Optimized.)
The last bit $('.status').on(...) will be fired each time someone clicks on a div. Then inside you see if it's green (online) or not and launch the appropriate function.
I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});
So... thanks to one of stackoverflow users I tried to implement this fancy feature into my existing Codeigniter application...
In my View I have this:
<script type="text/javascript">
$(function() {
$(".submit_op").click(function() {
var dataString = $("#op_form").serialize();
var url = "<?php echo site_url('submit/insert_data'); ?>";
$.ajax({
type: "POST",
url: url+"/"+dataString,
data: dataString,
cache: false,
success: function(html){
//$("div#op").prepend(html); //PROBLEM HERE???
$("div#op").prepend("<div>TEST</div>");
$("div#op div:first").fadeIn("slow");
//$("#debug").append("<font color=green><b>OK!</b></font> : " + dataString + "<br/>");
},
error: function(html){
//$("#debug").append("<font color=red><b>ER!</b></font> : " + dataString + "<br/>");
}
});
return false;
});
});
</script>
<div id="debug"></div>
<?php
//here goes some data from db... newly added div should go in top of other divs
foreach ($some_data_sent_from_controller as $var) {
echo "<div id=\"op\">";
echo "<table width=\"100%\" border=\"0\">";
//showing data
echo "</table>";
echo "</div>";
}
echo "<form action=\"#\" id=\"op_form\">";
//some clickable stuff...
echo br().form_submit('submit', 'OK', 'class="submit_op"');
echo "</form>";
In my Controller I have a function which handles data sent from View:
function insert_data($input) {
$this->load->model('blah_model');
//processing serialized data and sending it to corresponding tables via Model
$this->blah_model->add_to_table($some_data);
$this->blah_model->add_to_another_table($some_other_data);
}
And the Model is not a biggy :)
function add_to_table($data){
//processing data...
$insert = $this->db->insert('my_table', array('array_which_contains_actual_data'));
if ($insert == TRUE) {
return TRUE;
} else {
return FALSE;
}
}
//etc.
As far as I can tell, my problem is not in my M-V-C pattern, since every time I submit a form the data is correctly inserted in all possible tables in my relational db... But the newly added row just won't show up unless I refresh a page.
I think that I'm doing something wrong inside of my jQuery.ajax lines... If I run my script with this line $("div#op").prepend("<div>TEST</div>"); and when I submit a form, I get desired result - text TEST shows up on top of my page every time I submit... But if I change that line to $("div#op").prepend(html); nothing show up until refreshing...
What am I doing wrong here??
Thanks a lot for any help!
wow, this was probably pretty lame from me... But in the end I figured out that I have to echo out my result in controller, not return it... So when I change the function in my controller into
function insert_data($input) {
$str = "<div>KILLROY WAS HERE!</div>";
echo $str; // <----- !!!!!!
}
I can see a message on my page...
Now to other things... Thanks for self-brainstorming :)
I am have a table that shows the user suggestions that they have recieved on clicking read more some ajax is fired and in the database the suggestion is marked as read. Currently if the suggestion is new I show a closed envelope, if it is read I show an open envelope, however I can get it to reload the table when the user clicks the read more link so that the new class can be added. Currently it half works, they click read more and the full suggestions fades in but I need the envelope to change also.
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
$newRow = "new";
} else {
$newRow = "old";
}
?>
<tr id="a<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td class='".$newRow."'>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
} else {
echo "You have no new suggestions";
}
?>
</table>
</div><!--/popular-->
</div><!--/widget-->
<div id="readMore">
</div>
<script type="text/javascript">
$(document).ready(function() {
//alert("hello");
$('#tabvanilla').tabs({ fx: { opacity: 'toggle', height:'toggle' } });
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $(this).attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function(html) {
$('table').html()
}
});
return false;
});
});
</script>
In the JavaScript where you open/fill in the full suggestions, you can modify the envelope image as well, using something like:
$('#envelope').attr('src', 'src/to/envelope.png');
I see no img tags, so you need to add one and fill in the id, so it is found by the JavaScript.
BTW: Having HTML and PHP on the same lines/parts, makes the total very unreadable. Only use <?php ... ?> for large PHP code blocks, otherwise use echo (or something similar).