change css class after an if else statement of PHP query - php

The program refreshes the values of $pat_no every 5 seconds, what i want to know is, how can i change the css class property of the div being refreshed after the query is made. after comparing the values, the class will change accordingly(like changing the background color) if the value is changed in the database so that the changed value is easily noticed and reverts back to its old class after 5 seconds too.
Here's the code
<?php
include 'connect.inc.php';
$query = "SELECT patno, compare, cubeno FROM tblcube WHERE cubeid = '1'";
if($query_run = mysql_query($query)){
while($row = #mysql_fetch_assoc($query_run)){
$com = $row['compare'];
$pat_no = $row['patno'];
$cube_no = $row['cubeno'];
if($com == $pat_no){
//change css class of <th>
echo "<th>".$pat_no."</th>";
}
else if ($com != $pat_no){
//change css class of <th>
echo"<th>".$pat_no."</th>";
$query2 = "UPDATE tblcube set compare = '$pat_no'where cubeid = '1'";
if($query_run= mysql_query($query2)){
}
}
}
}
?>
Here is the JS code
function AJAX(){
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
}
also, here is the portion of index.php
<head><script src="ajax1.js"></script>
<script type = "text/Javascript">
refreshdiv_c1v();</script>
<body>
//cubicle1
$query = "SELECT patno, cubeno FROM tblcube where cubeid = '1'";
if($query_run = mysql_query($query)){
while($row = mysql_fetch_assoc($query_run)){
$pat_no = $row['patno'];
$cube_no = $row['cubeno'];
echo " <tr class = 'rows' id = 'cub1'>
<th class = 'name'>".$cube_no."</th>
<th class = 'num'><div id = 'c1v'>".$pat_no."</div></th>
</tr>";
}}
</body>

My guess is it would go something like this in your php file...
if($com==$pat_no){
return json_encode(array("msg"=>true,"data"=>$pat_no));
} else {
$query2 = "UPDATE tblcube set compare = '$pat_no'where cubeid = '1'";
if($query_run= mysql_query($query2)){
return json_encode(array("msg"=>false,"data"=>$pat_no));
}
}
And something like this in your jquery...
function checkPat(){
$.getJSON('yoururl.php',function(data){
if(data.msg==true){
// Update your class here
$('.theTRthatchanged').addClass('yourClass');
//Remove after 5 seconds
setTimeout(function(){
$('.theTRthatchanged').removeClass('yourClass');},5000);
} else if(data.msg==false){
//Do nothing I guess.
}
});
}
//Set the checker to fire every 2 seconds or whatever interval seems best.
setInterval(checkPat,2000);
Not quite exactly like this, but this is the main idea of how it would work. How you would go about selecting the tr that changed is up to you, and might be a bit tricky. You'll have to maybe attach data-id attributes or something of the sort, and send that back with the json.
But you get the idea.

Related

php javascript working to show one value in textbox but cant get the multiple

i have this code below of javascript:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","includes/get_user.php?q="+str,true);
xmlhttp.send();
}
</script>
and the php sql script is given below:
<?php
$testQrys = "SELECT * FROM test where status = 1";
$testdbResults = mysql_query($testQrys);
?>
<select size='5' width='925' style='width: 925px' name='users' onchange='showUser(this.value)' multiple>
<?php while($test = mysql_fetch_array($testdbResults )) { ?>
<option class='h4' value='<?php print($test[9]); ?>'>
<?php print($test[5]);echo" ( ";print($test[9]);echo" )"; ?>
</option>
<?php } ?>
</select>
<div id="txtHint"></div>
and the get_user.php code is:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','airways');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM test WHERE m_email = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<input type='text' name='staff_no[]' value='".$row['m_staff_no']."'>";
}
mysqli_close($con);
?>
now what i want is when i select one user in the select option it shows the staff no of that user but when i select multiple users it does not show the staff no of other users i select.
please help me with the change in code so i can get the staff no of users like (22344, 44333, 33344, 55443, 11125, 25263) in the text box
waiting for the kind and prompt responses.
Thanks in advance
The error is coming from showUser(this.value). This returns only the first selected element's value. You need to cycle through all options and concatenate them together to make a string that you will be able to send as a parameter.
Change your javascript code to something along those lines. Note that you will need to change your PHP code in order to separate the emails, sanitize them and create a working WHERE m_email IN () query.
You will need to add id="users" to your HTML code first.
var usersList = document.getElementById('users');
var emailString = '';
for (user_counter = 0; user_counter < usersList.options.length; user_counter++) {
if (usersList.options[user_counter].selected) {
emailString += usersList.options[user_counter].value;
}
}
Then send emailString as the parameter to the PHP script. Test it again with log.txt in case you get an error.

Limiting results from instant search in PHP?

I made a search bar, for searching users in my database, and I will share my code below. But one problem is that, if I have 5 users in a table, it shows these 5 users, but if I have 1,000 than it shows all 1,000.
Whatever I tried to limit it, it did not work. Sometimes it completely kills the PHP script.
Does anyone know how to solve that and limit to only 5 results displayed per search query from the code below?
HTML INPUT AND AJAX SCRIPT:
<input id="text" type="text" name="text" onkeyup="showHint(this.value)" autocomplete="off" />
<div id="inner" class="inner"></div>
<script>
function showHint(str) {
if (str.length==0) {
document.getElementById("inner").innerHTML="You haven't search. Please have :D";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("inner").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST","searchquery.php?text="+str,true);
xmlhttp.send();
}
</script>
AND searchquery.php:
<?
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
function connect($database) {
mysql_connect('localhost','root','');
mysql_select_db($database);
}
connect('developing');
$query = "SELECT * FROM users WHERE first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
if ($result == 0) {
$output = "User does not exist...";
}else{
while ($row = mysql_fetch_array($action)) {
$output .= '<div class="output"><img src="/'.$row['avatar'].'"><a href="#">'.$row['first_name'].' '.$row['last_name'].'</div><br />';
}
}
echo $output;
?>
Can anybody see some solution on how to make that limit?
Use LIMIT in your query:
SELECT *
FROM users
WHERE first_name LIKE '%$text%'
OR last_name LIKE '%$text%
LIMIT 5'

pagination using ajax

I have 2 pages
The first page for calling a second page to get all records from database, like this:
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(Mode,users_ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxDeleteRecord.php';
var pmeters = "tMode=" + Mode +
"&tusers_ID=" + users_ID;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
<body Onload="JavaScript:doCallAjax('LIST','');">
<form name="frmMain">
<div style="margin-right:10px">
<span id="mySpan"></span>
</div>
and the second page is php that fetches data:
$strMode = $_POST["tMode"];
$users_ID = $_POST["tusers_ID"];
if($strMode == "DELETE")
{
//$strSQL = "DELETE FROM users , stores WHERE users.users_StoreId=stores.stores_ID AND users.users_ID = '".$users_ID."'";
$strSQL = "update users set users_delete='1' where users.users_ID = '".$users_ID."'";
$objQuery = mysql_query($strSQL) or die (mysql_error());
}
$strSQL = "SELECT * FROM users , stores WHERE users.users_StoreId=stores.stores_ID and users.users_delete='0' ORDER BY stores.stores_Name , users.users_Type ASC ";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
The problem that I cannot make paging work for this.
Can any one help me?
Use Google's Visualization API's
table chart
Visualization: Table.
It will automatically enable paging as per your count like 10 or 20 and sorting your content ascending or descending on the basis of column.

PHP do not repeat last fetch

I have this code:
$result = mysql_query("SELECT * FROM quote ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['frase'];
It echo´s a random "frase" every time you query.
What I want to do is avoid having the same result in consecutive queries.
To make myself clear, if in my database I´ve got:
1 a
2 b
3 c
If from echo $row['frase']; I got a the the next result can´t be a.
I hope I made myself clear and if not please comment and I´ll expand!
Thanks in advance!
BTW: sorry to #deceze #zerkms #Dr.Molle because last question was a total mess! No harm ment, just a noob on a spree :)
EDIT:
To answer Jason McCreary I actually call it like this:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Since this last query needs to persist across page refreshes, you need to use a session. Something along these lines:
session_start();
if (empty($_SESSION['lastresult'])) {
$_SESSION['lastresult'] = null;
}
$query = "SELECT * FROM `quote` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query = sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$_SESSION['lastresult'] = $row['id'];
echo $row['frase'];
You may want to store the last x results in the session and use NOT IN () in your query to avoid every second (third, forth, ...) quote being the same.

php count error

As you see I have created drop down and give it name the field name, and I have also the count function.
What I want to do is, if some select drop down menu..show the how many result found in number like 10, 20,.. if the second dropdown selected it will check the two drop down selected and pass the result count..like that continuous..if you want to see example what exactly I want is go here and choose car the count will update..
http://en.comparis.ch/Carfinder/marktplatz/Search.aspx
I have the ajax and working well but I can't get the exact PHP code to count in live time.
AJAX Code..
var xmlHttp
function showCount(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="phpApplication.php";
url=url+"?action=count2";
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("countR").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
PHP Code
function dropdown($field, $table)
{
//initialize variables
$oHTML = '';
$result = '';
//check to see if the field is passed correctly
if (($field == "")||($table == ""))
{
die("No column or table specified to create drop down from!");
}
$sql = "select distinct($field) from $table";
//call the db function and run the query
$result = $this->conn($sql);
//if no results are found to create a drop down return a textbox
if ((!$result) ||(mysql_num_rows($result)==0))
{
$oHTML .= "<input type='text' name='$field' value='' size='15'>";
}elseif (($result)&&(mysql_num_rows($result)>0)){
//build the select box out of the results
$oHTML .= "<select name='$field' onchange='showCount(this.value)'>\n<option value='all'>All</option>\n";
while ($rows = mysql_fetch_array($result))
{
$oHTML .= "<option value='".$rows[$field]."' name='".$rows[$field]."'>".$rows[$field]."</option>\n";
}
$oHTML .= "</select>\n";
}
//send the value back to the calling code
return $oHTML;
}//end function
function count1(){
$sql2 = "SELECT SQL_CALC_FOUND_ROWS * from produkt_finder_table where Bauform_d ='".($_POST['Bauform_d'])."' ";
$query = $this->conn($sql2);
$result = mysql_query( $query );
$count = mysql_result( mysql_query( 'SELECT FOUND_ROWS()' ), 0, 0 );
echo $count;
//$sql2 = "SELECT COUNT(Bauform_d) from produkt_finder_table where Bauform_d = 'mobil' ";
//echo var_dump($result1);
while($row = mysql_fetch_array($query))
{
// echo $row['COUNT(Bauform_d)'];
}
//echo mysql_num_rows($query);
// if (isset($_POST['Bauform_d']))
//{
/* if (mysql_num_rows($result)==0) {
echo '0';
} else {
echo mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $result;
echo $row['COUNT(Bauform_d)'];
// }
}*/
}
$action = $_GET['action'];
$proFin = new Application();
switch($action) {
case 'show':
$proFin->show_form();
break;
case 'search':
$proFin->search();
break;
case 'searchAll':
$proFin->searchAll();
break;
case 'count2':
$proFin->count1();
break;
}
What parts have you debugged?
Change the count1() function to just echo back the time or something using time().
Then if it returns the correct value you know your JS is working and your PHP script is calling the correct function.
I assume that the PHP code doesnt work as the SQL query is looking for $_POST['Bauform_d'] which isnt set when you call the xmlHTTP Request. Run a simple print_r($_POST); to make sure you are passing all the data you expect in the query. If it is not then change your JS code to pass the value - when you are sure your php script is being passed all the correct variables then begin to add back in your SQL query etc.
debug debug
Jacob's answer is the key.

Categories