reload a table after link click to update results - php

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).

Related

How to use ajax to update label from count from mysql database

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();

PHP/AJAX check if div is clicked and return data

How is possible to check if div is clicked and then return information?
function kat(){
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
echo "</div>";
}
echo "<div class='mygtukas-js' onclick='kat();'>";
echo "</div>";
But actually it's wrong because my mygtukas-js has a drop down menu.
I need to generate a code which let me to press a button and then menu would be generated. Maybe someone knows?
EDIT: This div <div class='mygtukas-js'></div> (has to start and end before) <div class='turinys'> STARTS.
Some fresh ideas? :?
EDIT2:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>
<script>
$(document).ready(function(){
$('#mygtukas-js').click(function() {
$("#turinys").load('b.php');
});
});
</script>
and b.php
<?php
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
?>
But no information generated :(
Create your PHP file which I guess would also include HTML.
Create a "click" JQuery function and make sure to send the POST to the specific PHP file / Controller which should handle the request. In case you want to just get the above file directly then point to it.
It should be like:
$(document).ready(function(){
$('#send').click(function() {
$("#menu").load('URL_TO_YOUR_PHP');
});
});
Thanks to AJAX the "#menu" should be displayed and will contain whatever the PHP file sends back.
HTH.
U can use jQuery to check if a div is clicked. Like this:
$('.turinys').click(function(e) {
$(this).html("Add any html to the div");
});
Use to different php file. Lets call A.php and B.php. A.php contain the menu code.
A.php
<?php
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'>
<a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a>
</div>";
}
echo "</div>";
?>
B.php
<script>
function kat(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "A.php", false);
xhr.send(null);
// You can also check response status if you need.
var serverResponse = xhr.responseText;
document.getElementById('menu').innerHTML = serverResponse;
}
</script>
<?php
echo "<div class='mygtukas-js' onclick='kat();' id='menu'>";
echo "</div>";
?>

Parsing div id with variable

First of all I appreciate that all members are trying to help each other.
I want div content by id in my javascript function. I've got function and it works fine with one div and it's content. But now I've got multiple records from DB, so to make div unique I have done following. where $i=$i+1 in while loop
<div id="<?php echo 'fvd'.$i; ?>" class="fake-checkbox star-checkbox"><a id="<?php echo 'tvd'.$i; ?>" onclick="respuestas('<?php echo $user_id1;?>'); return false;" href="#">Add to favourites</a></div>
so here I generate fvd1, tvd1 for next record fvd2,tv2 and so on
Below function process user id and get response by Ajax call and change caption from Add to favourites to Added to favourites and add class name 'checked' which change text color.
function respuestas(str) {
var popID = str;
var gett = document.getElementById('tvd1').innerHTML;
if (gett == 'Add to favourites') {
$.post('personals/addfavourite.php', {
ref: popID
}, function (data) {
if (data == 'no') {
alert('Sorry! something gone wrong!')
} else if (data == 'yes') {
var d = document.getElementById("fvd1");
d.className = d.className + " checked";
document.getElementById('tvd1').innerHTML = 'Added to favourites';
}
});
}
}
Now how can I parse fvd2,tvd2 and so on in this function.
Any help will be much appreciated..Thanks
If you add your $i to the function parameters you can get each grouping dynamically
onclick="respuestas('<?php echo $user_id1;?>',<?php echo $i;?>); return false;"
and
function respuestas(str,num) {
...
var gett = document.getElementById('tvd'+num).innerHTML;
...
var d = document.getElementById("fvd"+num);
...
document.getElementById('tvd'+num).innerHTML = 'Added to favourites';
...
}
You can do
onclick="respuestas(this, '<?php echo $user_id1;?>');
and the first param would be the <a> so you can do
function respuestas(elm, str) {
elm.getAttribute("id");
}
or so. (Not sure about the DOM method name)
BTW why don't you just put the $i to the call as well? Or maybe I didn't get the question right? If not, pls explain.
If you need to access the elements, well then you already have the <a> in elm, and the <div> is in elm.parentElement.
Check HTML DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement

hide and show div when page loads based on result generated from php

I am doing API call to box.net.
I wanted to show data from the response into a table.
But sometimes response is empty.
that time i want to show user some message.
So my idea is to show div containing table when i get some response and disable div containing message. and vice versa.
I an new to jquery. Didn't find suitable examples.
I tried something from those examples,but it was not successful.
here is
if (sizeof($folder_entries) == 0)
{
echo '<script>';
echo '$("#message").show()';
echo '$("#content").hide()';
echo '</script>';
}
else
{
echo '<script>';
echo '$("#message").hide()';
echo '$("#content").show()';
echo '</script>';
}
How can i get that?
Thanks in Advance.
seems like you need straightforward javascript or jquery to show and hide the div
<script>
if (some condition..... )
{
document.getElementById("test").style.display = '';
}
else
{
document.getElementById("test").style.display = 'none';
}
</script>
<div name="test" id="test">
jQuery:
$(document).ready(function() {
$('#hideh1').click(function(){
$('div.showhide,h1').hide();
});
$('#showh1').click(function(){
$('div.showhide,h1').show();
});
$('#toggleh1').click(function(){
$('div.showhide,h1').toggle();
});
});

Stuck with Codeigniter and jQuery.ajax

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 :)

Categories