Auto refreshing unlimited divs - php

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 />");
});

Related

How to receive a PHP Table on AJAX, and display it inside a DIV?

I'm beginning to work with AJAX, and I'm struggling with the next few things.
I'm working in Wordpress, with custom tables.
By the way, that's why the global $wpdb is there.
First, I have a Select, when you choose an option, the ID value will get stored in a variable in jQuery. This is done by the
onchange="selectRequest(this)"
global $wpdb;
$Estado = $wpdb->get_results("SELECT * FROM cor_estado;");
?>
<p>Busqueda por Estado</p>
<select class="select" id="estado" name="estado" value="" type="text" onchange="selectRequest(this);">
<option value="" disabled selected>Seleccione un estado...</option>
<?php
foreach ($Estado as $Estados ) {
echo "<option value='".$Estados->estado_id."' type='text'>".$Estados->nombre_estado."</option>";
}
?>
</select>
The Select will fill up with the id on value and the name.
This is my jQuery, but I'm having a problem here, if I leave everything on the jQuery(document).ready(){CODE HERE}, the Function selectRequest(id), won't work at all, I don't know if that has anything to do with the way that I am getting the id from the select.
Here it changed, now I am trying to receive HTML, I created the complete table on "table.php", and now I am trying to get it back
<script type="text/javascript">
function selectRequest(id){ // id of select
var selectVal = jQuery(id).val(); // currently selected
selectVal = selectVal.toString();
alert(selectVal);
jQuery.ajax({
type:"POST",
url:"<?php echo get_template_directory_uri(); ?>/table.php",
dataType: "html",
data:{selectVal:selectVal},
success:function(resultHtml){
jQuery("#resultado").html(resultHtml);
},
error:function(resultHtml){
alert("What follows is blank: " + data);
}
});
}
</script>
my PHP is like this at the moment, one big change was in the WHERE, since I am using an INNER JOIN, I needed to specify on which table the "estado_id" was going to be, since Wordpress uses table prefix, it was necessary to add it in this place too.
Like I said before, I decided to build the table here, and send it to AJAX with an echo, I created $table, and each time something was created inside the table, I added it with ".=".
Testing this inside the table.php without the "If(isset($_post['selectVal']))", and having an static ID it worked on the table.php document, but if I echo $table, I get nothing on AJAX, it appears as blank.
<?php
//table.php
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
}
?>
This is the HTML div where I want to display the echo $table content. At the moment if I select an option, the only thing that happens is that the P element disappears.
<div id="resultado">
<p>Estado Seleccionado</p>
</div>
The new problem is receiving this echo $table and displaying it where AJAX receives it.
instead of receiving data in JSON format, use HTML formatted data & replace your data directly in table. Using that your base issue "the amount of information in them will be different on each select option" will be resolved.
There's not a fixed rule... Sometimes is faster to create the html in the php and return it formatted so you can show it directly and sometimes is better to return raw data and handle it in javascript/jquery.
If the data you get from the ajax request is just for showing and you don't need to modify anything that depends of other elements in your current view, I will format the html response directly in the php. If you need to change something, then maybe I will go with JSON.
In your ajax request you establish JSON as the data format, so the response in your PHP has to be JSON. You almost have it. Uncomment the foreach but instead of independent variables ($info1, $info2) create an array with the fields you need for your response, and set key names. For example...
$response = array();
foreach ($Estado as $row) {
$response['municipio'] = $row->nombre_municipio;
$response['estado'] = $row->nombre_estado;
.....
}
Once you have the array created, convert it to JSON and return with...
print_r(json_encode($response));
Then, in your jquery ajax success function you can access each field with...
data.municipio or data['municipio']
data.estado or data['estado']
...
I hope it helps
So, the basic problem here was that I was following the steps to do this using the tools (JS, PHP, HTML and CSS) outside the Wordpress environment, this was the issue. I'm still solving some aspects about my AJAX request, I will try to update this answer as fast as I can.
In this Wordpress Codex entry, they explain it in detail.
Basically Wordpress has it's own way of using AJAX, so no matter if this 'looked' correct to me, the Wordpress site wasn't going to display anything from it.
Here is the solution that I used to solve my problem.
<!-- language: lang-js -->
UPDATED CODE
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal},
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
STEP #1
/wp-admin/admin-ajax.php //will be the URL for all your custom AJAX requests.
This is absolutely necessary, because this document verifies the AJAX 'actions', and points them to your functions.php
STEP #2
data:{action:'your_action_name', val1: 1, val2: 2 ...}
The first variable that you have to send will always be action, the value can be the anything you want.
As I said earlier, admin-ajax.php looks for the variable action when it receives an AJAX request from any file, it will look for action, once it finds it, it will redirect it to the functions.php file located inside your_theme folder.
STEP #3
Inside you functions.php file, you will add the PHP code as a function, like this:
<!-- language: lang-sql -->
function selectEstado(){
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
wp_die();
}
}
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
STEP #4
Inside your functions.php file you will create a function, can be called whatever you want, for example 'your_function_name'.
To access easily to the database, Wordpress uses the variable $wpdb, by including the line like this global $wpdb; now you can use it to access the database without any problems.
Now you have to check if the values after action got there, the if(isset($_POST)) will take care of it. To check the Database, you use the $wpdb->get_result("");
Basically what I am doing with the INNER JOIN, is checking a column name, and checking where the two tables match, and then pulling the rest of the columns that the element on the table has in "cor_municipio" and "cor_estado".
(In this code I am using JOINS, if you want to know more about them, I'll leave a link below)
Here they explain JOINS with Venn diagrams
Then I created a variable that each time a part of the table was created, it was being added to it.
You echo your data, and don't forget "wp_die();"
STEP #5
This is the last part to have your AJAX request working on Wordpress.
The next two lines are very important for it to work, this is the action that admin-ajax.php is looking for, and it's here that it references it's value, these lines look like this for every new AJAX request you need to make:
add_action('wp_ajax_', '');
add_action('wp_ajax_nopriv_', '');
this is the "default" way the lines are written, but you will need to complete them with two things.
The action value you used in the AJAX request, in my case is 'my_action', or in this example 'your_action_name'.
The second value is the name of the function created inside your functions.php file.
It will end up looking like this for me:
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
Using the value of 'your_action_name' and 'your_function_name':
add_action('wp_ajax_your_action_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name');
The first line is for logged in users, and the second one is for visitors, if you want to display something different for logged in users and another one for visitors, you will need to create a function for each of them, and just use one attribute.
add_action('wp_ajax_your_action_name', 'your_function_name1'); // for registered users
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name2'); // for visitors
Again, this is PHP code written in admin-ajax.php, if you want to look deeper into it.
I already found out my problem, when I was sending the data on the first time I was using:
data:{action:'my_action', selectVal: 'selectVal'},
Basically what I was sending to Wordpress on selectVal, was the string
selectVal
So when my function tried to find the id based on the receiving data, it wasn't going to find anything, because it was a string with those letter.
SOLUTION
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal}, // The right way to send it
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
What I am sending now is the value, and now my AJAX success:function, receives the complete table, I also changed the jQuery code, because in the first example, when adding ".hide() or .show()", it was sending multiple errors.
To add conditions by user role you can edit the admin-ajax.php to make it simpler for all the AJAX requests.
I know is way too long, but if you were having some trouble, I wanted to explain all the different elements that are used, to make it easier to understand what is happening with AJAX in Wordpress.

Javascript countdown not working for php loop

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.

MySQL Query not returning newest results on setInterval

I am having a problem with setInterval in the $(document).ready(function(){}
What I am doing is setting the interval to do is call a PHP script that runs some MySQL queries to check the condition of 4 switches and then updating the screen with the values are in the database like so:
$(document).ready(function(){
setInterval(function(){
<?php require('fetchSwitchStatuses.php'); ?>
$("#switch1").css('background', 'rgb(<?php echo $switchColor1 ?>)');
$("#switch1").html('<?php echo $switchState1 ?>');
$("#switch2").css('background', 'rgb(<?php echo $switchColor2 ?>)');
$("#switch2").html('<?php echo $switchState2 ?>');
$("#switch3").css('background', 'rgb(<?php echo $switchColor3 ?>)');
$("#switch3").html('<?php echo $switchState3 ?>');
$("#switch4").css('background', 'rgb(<?php echo $switchColor4 ?>)');
$("#switch4").html('<?php echo $switchState4 ?>');
},1000);
});
Here is the code for fetchSwitchStatuses.php:
$connect = mysqli_connect("localhost", "root", "root");
mysqli_select_db($connect, "db_name");
$fetch1 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '3'"
);
$fetch2 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '5'"
);
$fetch3 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '6'"
);
$fetch4 = mysqli_query($connect,
"SELECT SwitchStatus FROM Switches WHERE PinNumber = '9'"
);
$i = 1;
while($row = mysqli_fetch_array(${'fetch'.$i}))
{
if($row['SwitchStatus'] == 0)
{
${'switchColor'.$i} = "255, 0, 0";
${'switchState'.$i} = "OFF";
}
else if ($row['SwitchStatus'] == 1){
${'switchColor'.$i} = "0, 255, 0";
${'switchState'.$i} = "ON";
}
else {
${'switchColor'.$i} = "100, 100, 100";
${'switchState'.$i} = "ERROR";
}
$i++;
}
mysqli_close($connect);
When the page is loaded the information is correct, whatever is in the database is what is reflected by the colors on the screen.
When I click on the object to change the value, all of the necessary changes are made and the database is updated. However, the problem arises when the Interval is repeated. The values are switched back to whatever the original values were when the page was loaded. So, although the information is correctly changed in the database, for some reason the colors of the buttons is always reset to the first value read by the queries.
How can I fix this so that the information that is reflected on the screen is accurate?
With AJAX technology you can:
Send a request and get results from server by requesting a page (a .txt .js .html or even php).
So with AJAX you can get result of a page save something to database, get something from data base, you can work with sessions and anything you can do with a php file.
When you send an AJAX request to a see a page(i.e /userData.php?userId=5) the page /userData.php?userId=5 will be executed and its output will be returned.(HTML or just a word ‘yes’ or ‘no’ or ‘you can’t access to this user’s information’).
You can send data to file with POST or GET. But the question is how you can get data from page. Because the result AJAX will give you is what the requested page echoed to page like this
<html>
….
</html>
Or
‘Yes’
Or
<?php echo ‘something’; ?>
So what about getting a row of Date or lots of data? Because the only thing you are getting is a text or maybe a long text.
For that you can use JSON which Is something like nested arrays.
[
{
"term": "BACCHUS",
"part": "n.",
"definition": "A convenient deity invented by the...",
"quote": [
"Is public worship, then, a sin,",
"That for devotions paid to Bacchus",
"The lictors dare to run us in,",
"And resolutely thump and whack us?"
],
"author": "Jorace"
},
…
And this is a string too. But you can get Data in it with $.getJSON in jQuery and you can generate JSON data in server side like this.
<?php
$arr=array(
‘data’=>’ffff’,
‘anotherData’=>array(‘rrrrr’,’sssss’);
);
Echo json_encode($arr);
?>
Json_encode() in PHP gets an array and returns json string of it. And we echo it.
Now we can use jQuery to get Data which will be retrieved from server.
This section if from
Learning jQuery 1.3
Better Interaction Design and Web Development with Simple JavaScript Techniques
Jonathan Chaffer
Karl Swedberg
Global jQuery functions
To this point, all jQuery methods that we've used have been attached to a jQuery object that we've built with the $() factory function. The selectors have allowed us to specify a set of DOM nodes to work with, and the methods have operated on them in some way. This $.getJSON() function, however, is different. There is no logical DOM element to which it could apply; the resulting object has to be provided to the script, not injected into the page. For this reason, getJSON() is defined as a method of the global jQuery object (a single object called jQuery or $ defined once by the jQuery library), rather than of an individual jQuery object instance (the objects we create with the $() function).
If JavaScript had classes like other object-oriented languages, we'd call $.getJSON() a class method. For our purposes, we'll refer to this type of method as a global function; in effect, they are functions that use the jQuery namespace so as not to conflict with other function names.
To use this function, we pass it the file name as before:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
This code has no apparent effect when we click the link. The function call loads the file, but we have not told JavaScript what to do with the resulting data. For this, we need to use a callback function.
The $.getJSON() function takes a second argument, which is a function to be called when the load is complete. As mentioned before, AJAX calls are asynchronous, and the callback provides a way to wait for the data to be transmitted rather than executing code right away. The callback function also takes an argument, which is filled with the resulting data. So, we can write:
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
});
return false;
});
});
Here we are using an anonymous function as our callback, as has been common in our jQuery code for brevity. A named function could equally be provided as the callback.
Inside this function, we can use the data variable to traverse the data structure as necessary. We'll need to iterate over the top-level array, building the HTML for each item. We could do this with a standard for loop, but instead we'll introduce another of jQuery's useful global functions, $.each(). We saw its counterpart, the .each() method, in Chapter 5. Instead of operating on a jQuery object, this function takes an array or map as its first parameter and a callback function as its second. Each time through the loop, the current iteration index and the current item in the array or map are passed as two parameters to the callback function.
$(document).ready(function() {
$('#letter-b a').click(function() {
$.getJSON('b.json', function(data) {
$('#dictionary').empty();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="term">' + entry['term'] + '</h3>';
html += '<div class="part">' + entry['part'] + '</div>';
html += '<div class="definition">';
html += entry['definition'];
html += '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
return false;
});
});
Before the loop, we empty out so that we can fill it with our newly-constructed HTML. Then we use $.each() to examine each item in turn, building an HTML structure using the contents of the entry map. Finally, we turn this HTML into a DOM tree by appending it to the .
This approach presumes that the data is safe for HTML consumption; it should not contain any stray < characters, for example.

Using one <form>'s selection to feed into another <form>?

From within php, I have a large html <form> filled out with lots rows of patient info from a postgres database. When a doctor double-clicks on a row, it sets a var in $_POST and invokes another php script to read up and display specific info about that row from the database. This all works.
But there are now so many rows of patient data that the doctors don't want to scroll and scroll to find the patient rows they're looking for, they want a patient prefilter <form> so that a click on an element in it will result in the large display filtered to just that patient's rows.
What's a basic approach to doing this? I'm a newb; I'm currently using html, php, and some javascript.
Make a second form with whatever options you'd like to filter on, this part will be specific to your data but you want something like
<form id="search-form">
<label>Name:</label><input type="text" name="patient-name"></input>
</form>
You'll need to build a query string (and make sure you use GET, because that will make things easier for you). This will require tweaking if you want to use radio buttons, or something similar, but here's the general idea:
function getSearchParameters () {
var form = document.getElementById('search-form');
var inputs = form.getElementsByTagName('input');
var result = '';
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value) {
result += "&" + inputs[i].name + "=" + inputs[i].value;
}
}
return result;
}
In the onClick handler for your patient data links, you'll call this function and append its result to your query string:
element.onclick = function () {
var patientDataUrl = '/patients.php?param1=someValue';
patientDataUrl += getQueryParameters();
/* then do your ajax stuff as normal */
};
Then on the server side, within patients.php simply check for the presence of the search fields i.e.
if(isset($_GET['patient-name'])) {
$patient_name = mysql_real_escape_string($_GET['patient-name']);
$query = "SELECT * FROM `patients` WHERE `patient_name`='$patient_name';";
} else {
$query = "SELECT * FROM `patients`;";
}
(make sure you sanitize the string!)
I'd recommend considering a JS framework to make your life much easier (for instance, jQuery would allow you to send this via POST or easily serialize it into a GET query string via .serialize())

Check message inbox dynamically with ajax?

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

Categories