I'm almost done coding a website that i had started a few months ago. I have the foundation done but, i wanna add some new features to it to make it quicker and add some bling to it.
Currently, I have system whereby php queries the db to see if there are any unread messages every time the page a new page request is made. if a user has an unread message, php echoes the number of unread messages inside of a quotations.
How could I use ajax or jquery to echo out the number of undread messages without having to make a new page request?
thanks
You could set a timed request, like this:
var element = $('...');
// new get request every minute - 60*1000ms
var interval = setInterval( function(){
element.load('/phpfile.php');
}, 60000 );
In your /phpfile.php
Output results and encode array to json format. For example you may have query
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT message FROM messages";
$result = mysql_query($query);
$jarray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$jarray[] = array("message"=>$row['message']);
}
echo json_encode($jarray);
include 'closedb.php';
?>
Get json array with ajax.
var messagesContainer = $('messages');
$.getJSON('phpfile.php',function(data)
{
$.each(data, function(i,stuff){
$("<div class='msg'>"+stuff.message+"</div>").prependTo(messagesContainer);
}
})
Create a script that only echoes the number of unread messages (without any other HTML) and then use jQuery to get it:
$('#span_with_numer_of_messages').load('your_unread_messages_script.php');
Related
I have a simple Server-sent event setup I'm trying to make display as a table. Currently I have the SSE php page pulling the data out of the MySQL table and sending the data over as a Json array to the live page. How would I be able to take the Json array and put that into a html table with out sending the array back as a post and causing the page to "refresh"?
Here is my current code
SSE.php
//get MySQL data
$new_data = getVar();
//Create Array
$data_array = array();
//add data to array
while($row = $new_data->fetch_assoc()){
$data_array[] = $row;
$out = array_values($data_array);
$new_out = json_encode($out);
}
//echo the array to html page
echo "data: $new_out \n\n }'";
Index.html
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
//document.getElementById("serverData").innerHTML = event.data;
};
Where serverData is the div where the array is currently being shown
I have tried to echo data: multiple times or echo the html markup back but I couldn't make it work with out a php runtime error
thanks
You may want to make an AJAX request to the PHP script. This will allow the data from the database table to populate your page without refreshing. Check out this W3Schools example.
You can simplify the user defined JavaScript by using jQuery's AJAX functions (though you would have to load jQuery onto your page as well).
The overall goal is to relay information from a mysql server via a php file to the webpage being viewed. More specifically I want to target certain aspects of the php file, or certain tables in the database, and display them in different divs on the webpage. Given my limited experience I'm not sure how best to do this but I would imagine the flow would be something like this...
(I apologize for the limited code detail but everything I tried didn't seem like the right approach so I'll keep it broad so it can be open to suggestions.)
Call php file and request certain variables such as:
$(document).ready(function(){
//call sqlrelay.php
//ask for some variable ($row) or some section of the code (within the if statement)
//display it in div ('#collapseOne')
};
Listen with the php file (sqlrelay.php) such as:
<?php
//if request received from client side do this:
include ("connection.php");
$sendtable = "SELECT timein FROM timestamp1 ORDER BY id DESC LIMIT 1";
$result=mysqli_query($link, $sendtable);
$row = mysqli_fetch_array($result);
$table = $row['timein'];
echo $table;
<?
Look the API: http://api.jquery.com/jquery.ajax/
or use my code.
$(document).ready(function() {
$.ajax({
method: "POST",
url: "sqlrelay.php",
data: {
row: "your query"
},
success: function(data) {
$('#collapseOne').html(data);
}
});
});
and your PHP looks like this to catch the row request
<?php
$row = $_POST['row'];
echo $row;
Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.
I am currently able to refresh a div on my website using jquery with php. This works well to a point. The issue is that the data being refreshed currently is an entire table. The code being used in the header is as follows:
<!-- DIV REFRESH START -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#datatable').fadeOut('slow').load('data/table.php').fadeIn("slow");
}, 10000);
</script>
<!-- DIV REFRESH END -->
As you can see, it is refreshing a specific div with a specific page. I'm very novice with jquery and java based coding in general as I'm sure will be evident in this question.
Is it possible to do the following:
The table is actually created in a php function due to the the fact that the number of rows changes all the time. Is it possible to have it refresh the function specifically rather than a page that is just calling the function?
The table currently refreshes completely. This is just to update one figure on each row. It would be much cleaner to have it only refresh each figure on the row but due to the flexible nature of the table and the fact that it is part of a function would this be possible? If so, how would it be possible? I know I could have each div on each row to have a unique div name which I could then take into account in the script section at the top of the page but would that not require having every possible div name added with the same code repeated?
Though I know it is possible to have the item refresh based on when something in the database changes rather than by a time delay but what would be the best way given the requirements listed above?
I could be way off and it's a simple answer to each question but I appreciate any and all input.
Thanks!
p.s. if it helps, the function I'm currently using to create the table is the following (I know it can be made to function much cleaner but it is a bit of a learning project):
function portalTable($venueId, $eventId)
{
echo "<table class='basic-table'><tr class='th'><th>Portal Name</th><th>Scanned</th></tr>";
$grandTotals = array();
$portalSql = mysql_query("SELECT * FROM portal WHERE id_venue = $venueId");
while ($portalRow = mysql_fetch_array($portalSql))
{
$portalId = $portalRow['id_portal'];
$portalName = $portalRow['name_portal'];
if($portalId&1) {$gray = "dg";} else {$gray = "lg";}
$sql = mysql_query("SELECT * FROM scan WHERE id_event = $eventId AND id_portal = $portalId");
while ($row = mysql_fetch_array($sql))
{
$scanTotal = $row['total_scan'];
echo "<tr class='$gray'><td>$portalName</td><td>$scanTotal</td></tr>";
$grandTotals[] = $scanTotal;
}
}
$totals = array_sum($grandTotals);
echo "<tr class='basic-table-total'><td>Total</td><td>$totals</td></tr>";
// total failed scans
$sql = mysql_query("SELECT total_errors FROM errors WHERE id_event = $eventId");
while ($row = mysql_fetch_array($sql))
{
$totalErrors = $row['total_errors'];
echo "<tr class='basic-table-total'><th>Total Rejected Scans</th><th>$totalErrors</th></tr>";
}
echo "</table>";
}
$('div.myDiv').each(function(i, obj) {
$(obj).load('myURL.php');
});
That what you're looking for?
As for the large amount of data being sent? Don't send raw HTML!
Instead, use parseJSON in jQuery and json_encode in your PHP script to send a (much) smaller amount of data to the user, which can then be used by the client to make the table.
Handling the decoded JSON data is relatively simple in JavaScript. Once it has been decoded, it is now an accessible object. You can use an iterator (jQuery does this well).
$.each(myJSON, function(i, val) {
$('body').append(val + "<br />");
});
I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/