Refresh with ajax and php - php

I'm working on being able to refresh a div that contains data from a database.
I have established this code here but when I open the F12 console, this error appears:
Uncaught ReferenceError: $ is not defined
at loadlink (index.php:29:17)
at index.php:34:13
I have two files an index file and a commands file or on the index file I will include a commands.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<div class="commandes">
<?php
$sql = "SELECT enc_id, enc_cmd_num, enc_paye, enc_prepared, enc_ext_ref, enc_heure_fab_deb, enc_type, enc_heure_fab_fin, Client.cli_civilite,Client.cli_nom, Client.cli_prenom FROM Client RIGHT JOIN encaissement ON Client.cli_id = encaissement.enc_client WHERE enc_etat<>4 AND enc_date= convert(date,getdate()) AND ((DATEDIFF(n,enc_heure_fab_fin, getDate()) < 3 AND enc_prepared <> 0) OR enc_prepared = 0) AND enc_emporte <> 1 ORDER BY encaissement.enc_heure_fab_deb ASC";
$results = odbc_exec( $conn, $sql );
?>
<table>
<?php
while( $row = odbc_fetch_array( $results ) )
{
printf('<tr>');
if ( $row["enc_ext_ref"] != '')
{
$num_cmd = $row["enc_ext_ref"];
}
else
{
$num_cmd =$row["enc_cmd_num"];
}
if ($row['enc_paye'] = 0)
{
$etat_cmd='<span class="PRETE">ATTENTE REGLEMENT</span>';
}
else
{
switch( $row['enc_prepared'] )
{
case 0: $etat_cmd='<span class="ENPREPA">EN PREPARATION</span>'; break;
case 1:
$etat_cmd='<span class="PRETE">COMMANDE PRETE</span>'; break;break;
}
}
switch( $row['enc_type'] )
{
case 0: $commande='<span class="EMPORTER"></span>'; break;
case 1: $commande='<span class="LIVRAISON"></span>'; break;
case 2: $commande='<span class="SURPLACE"></span>'; break;
}
printf('<td>%s%s%s</td>',$row["enc_cmd_num"],$etat_cmd, $commande);
}
?>
</table>
</div>
<script>
function loadlink(){
$('#commandes').load('commandes.php', function() {
});
}
loadlink();
setInterval(function(){
loadlink()
}, 10000);
</script>

Put
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
before <script>

Related

Autocomplete does't work properly in ci

controller: welcome.php
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX')
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}
view: index.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>resource/css/jquery-ui.css">
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
</head>
<body>
<input type="text" class="search-bg__text" name="tutorial_name" id="tutorial_name">
<script src="<?php echo base_url(); ?>resource/js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#tutorial_name").autocomplete({
source:"<?php echo base_url(); ?>welcome/lookup",
minLength:1,
select:function(b,c)
{
var a=c.item.value;
a=encodeURIComponent(a);
location.href=a+"-tutorial";
return false
}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
</body>
</html>
model: Main_tutorial.php
public function lookup($keyword)
{
$this->db->select('tutorial_name')->from('tutorial');
$this->db->like('tutorial_name',$keyword,'after');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
In this code I want to create an autocomplete suggestion box using codeigniter. Now what happen when I write something inside the tutorial_name input field and inspect the element then select network and click on link it show me the output but can't see on display I don't know why ?. So how can I fix this issue ?Please help me.
Thank You
In autocomplete() you need output as json format. Here you are printing json data with echo json_encode($data['auto_com']); But before it you are also displaying data print_r($query);. Which create invalid json output. so you have to remove it. Also note that your if('IS_AJAX') will always become true
public function lookup()
{
$keyword = trim($_GET['term']);
$data['response'] = 'false';
$query = $this->Main_tutorial->lookup($keyword);
if( ! empty($query) )
{
$data['response'] = 'true';
$data['message'] = array();
$data['auto_com'] = array();
foreach( $query as $row )
{
$data['message'][] = array('tutorial_name' => $row['tutorial_name']);
$data['auto_com'][] = $row['tutorial_name'];
}
}
if('IS_AJAX') //This condition always become true
{
echo json_encode($data['auto_com']);
}
else
{
$this->load->view('index',$data);
}
}

Data still not displaying using jqGrid after doing some tips found around the net

I'm still having difficulty displaying data using jqGrid. I found some resources that might help me like the one found here and even copying the code found here.
I've been trying to solve this for so many hours but still I fail to do so. Can someone please help me? The following are the codes I currently have:
HTML/Javascript code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" media="screen" href="css/smoothness/jquery-ui- 1.10.3.custom.min.css"/>
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css"/>
<style>
html, body {
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script type="text/javascript" src="js/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="js/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="js/jquery.jqGrid.min.js"></script>
<script type="text/javascript">
jQuery().ready(function (){
jQuery("#adminlist").jqGrid({
url:'cnc_admin_search.php',
datatype: "json",
colNames:['Record ID','Admin ID', 'Password', 'Last Name','First Name','Type Code'],
colModel:[
{name:'id',index:'id', width:55},
{name:'adminid',index:'adminid', width:90, jsonmap:"adminid"},
{name:'adminpass',index:'adminpass asc, adminid', width:100},
{name:'lname',index:'lname', width:80, align:"right"},
{name:'fname',index:'fname', width:80, align:"right"},
{name:'admintype',index:'admintype', width:80,align:"right"}
],
rowNum:10,
rowList:[10,20,30],
pager: '#adminpager',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
jsonReader: {
repeatitems: false,
id: "id",
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
caption: "JSON Mapping",
height: '100%'
}).navGrid('#adminpager',{edit:false,add:false,del:false});
});
</script>
<title>Administrator Panel - Super Administrator</title>
</head>
<body>
<header>
<h2>Administrator Panel - Super Administrator</h2>
</header>
<div class="content">
<table id="adminlist"><tr><td></td></tr></table>
<div id="adminpager"></div>
</div>
<footer></footer>
</body>
</html>
PHP/Database Code:
<?php
$page = 1; // get the requested page
$limit = 10; // get how many rows we want to have into the grid
$sidx = 0; // get index row - i.e. user click to sort
$sord = 'desc'; // get the direction
if(!$sidx) $sidx =1;
// connect to the database
$db = mysql_connect('localhost', 'root', '')
or die("Connection Error: " . mysql_error());
mysql_select_db('caneco_db') or die("Error conecting to db.");
$result = mysql_query("SELECT COUNT(*) AS count FROM caneco_admintable");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * FROM caneco_admintable ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldnt execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]=$row;
$i++;
}
json_encode($responce); // coment if php 5
break;
?>
I hope someone will be able to help me. Thank you.
UPDATE:
I included the json data encoded by my php file:
{"page":1,"total":1,"records":"2","rows":[{"Admin_UserNum":"751497003","Admin_UserID":"jrmthibaler","Admin_Passwrd":"44c8ac3a1f03f006febc1075b2ba567d","Admin_LastName":"Hibaler","Admin_FirstName":"Jairo","Admin_TypeCode":"1"}, {"Admin_UserNum":"704006278","Admin_UserID":"rojaihibaler","Admin_Passwrd":"8810534d4f44d557d92a2110d664dcf6","Admin_LastName":"Hibaler","Admin_FirstName":"Jairo","Admin_TypeCode":"2"}]}
This was the JSON data produced by the php file I included previously. However there's an error saying 'Creating an object from empty value in Line 25' namely the following line of code:
$responce->page = $page;
What could possibly be wrong with that line of code? The other two similar lines of code didn't generate the same error.

How to toggle external CSS on button click

I am facing one problem, I want to do something like this:
I want to toggle the EXTERNAL CSS when user is click on toggle button.
There are 5 different pages; there are:
Header
Footer
Main page
Contact us
About us
and I have 2 external style sheets:
style.css
style1.css
By default style.css is loaded.
Now when I click on toggle button then style1.css has to load, and when again click on toggle button style.css has to load and visa verse. I want to do something like this.
Is there anyone have an Idea regarding this. Please help me out!
CSS is loaded on header so when I click on toggle button I want to apply new style.css.
the problem i am facing is that when i am clicking on any other page at that time the default css is set but in my case i don't want that By default style.css is loaded now when user click on button style1.css is loaded now when user again click on button style.css is loaded when click again style1.css loaded and again style.css loaded i want to do something like this and this changes should be there for whole website of main! thnx for your valuable reply and wait for more accurate –
By doing something like this:
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
See Applying stylesheets dynamically with jQuery
DEMO
See Stylesheet Switcher jQuery
<script src="script/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
if ($.cookie("css")) {
$("link").attr("href", $.cookie("css"));
}
$(document).ready(function () {
$("#nav li a").click(function () {
$("link").attr("href", $(this).attr('rel'));
$.cookie("css", $(this).attr('rel'), { expires: 365, path: '/' });
return false;
});
});
</script>
<ul id="nav">
<li>Original CSS</li>
<li>Larger Text</li>
<li>Something Different</li>
</ul>
try this
$("#btntoggle").click(function(){
if($("LINK[href*='style.css']").lenght() > 0){
$("LINK[href*='style.css']").remove();
addCss(path + "style1.css");
}else{
$("LINK[href*='style1.css']").remove();
addCss(path + "style.css");
}
});
function addCss(path){
var headID = $("head").get(0);
var newCss = document.createElement('LINK');
newCss.rel = 'StyleSheet';
newCss.type = 'text/css';
newCss.href= path;
newCss.media = 'screen';
headID.appendChild(newCss);
}
Note that i've added the default style sheet in the markup, in case the user got JS disabled. So you get some kind of a fallback.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style1.css">
<script type="text/javascript" src="../jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#change").click(function(){
$('head link').each(function(){
if($(this).attr('rel') == "stylesheet"){
if($(this).attr('href') == "style1.css"){
$(this).attr("href","style2.css");
} else {
$(this).attr("href","style1.css");
}
}
});
});
});
</script>
</head>
<body>
<button id="change">Change</button>
</body>
</html>
$url = Mage::helper("core/url")->getCurrentUrl(); // $url contain your current url
if(!isset($_SESSION['cssfile']) and !isset($_GET['l']))
{
/*$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$i=1;
for(;$i<count($urlArr);$i++)
{
$tmpUrl .= $andP.$urlArr[$i];
$andP = '&';
}
if($i>1)
$tmpUrl .= '&l=1';
else
$tmpUrl .= 'l=1';*/
//$urlGet = $tmpUrl;//$url."?l=0";
$_SESSION['cssfile'] = '1';
}
if(isset($_GET['l']) and $_GET['l']==0)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '0';
}
else if(isset($_GET['l']) and $_GET['l']==1)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '1';
}
if(isset($_SESSION['cssfile']))
{
$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$found = 0;
//for($i=1;$i<count($urlArr);$i++)
foreach($_GET as $key => $val)
{
if($key == 'l')
{
$found = 1;
if($val == 1)
$val = 0;
else
$val = 1;
}
$tmpUrl .= $andP.$key.'='.$val;
$andP = '&';
}
if($found == 0 && count($_GET)>0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= '&l=0';
else
$tmpUrl .= '&l=1';
else if($found == 0 && count($_GET)==0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= 'l=0';
else
$tmpUrl .= 'l=1';
$urlGet = $tmpUrl;
}
/*if(isset($_SESSION['cssfile']) and $_SESSION['cssfile'] == 'styles1.css' )
{
$_SESSION['cssfile'] = 'styles.css';
$_SESSION['cssfile']
}
else
{
$_SESSION['cssfile'] = 'styles1.css';
}*/
//echo '--'.$_SESSION['cssfile'];
if($_SESSION['cssfile'] ==1){
?>
<link href="<?php echo $this->getSkinUrl()?>css/styles1.css" rel="stylesheet" type="text/css" id="style" />
<?php }else{ ?>
<link href="<?php echo $this->getSkinUrl()?>css/styles.css" rel="stylesheet" type="text/css" id="style" />
<?php } ?>

Jquery Autocomplete with PHP

I have been messing with this for too long trying to get it to work. Can anyone please see if you have any pointers.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: "autocomplete.php",
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
and the php file is
require_once "db_con.php"; // Database connection, I know this works.
$q = strtolower($_GET["q"]);
if (!$q)
return;
$sql = "SELECT * FROM materials WHERE name LIKE '%$q%'";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
I am trying to have a webpage with an autocomplete powered by Jquery that is supplied data from mysql using PHP. Simples. Only its not working...
Anyone have any ideas what I am missing ?
Regards
---- EDIT ----
In order to check this was working I completed the following:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: <?php
include_once 'db_con.php';
$sql = "SELECT name FROM materials";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
echo '[';
while ($rs = mysqli_fetch_array($rsd)) {
echo "'" . $rs['name'] . "', "; //add results to array
}
echo ']';
?>,
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
Which works perfectly. So good infact I think im going to keep this code not quite how its supposed to work but...
Try this code, Its works for me
$().ready(function() {
$("#materials").autocomplete("autocomplete.php", {
width: 260,
matchContains: true,
autoFill:true,
selectFirst: false
});
});
In the PHP part, maybe try something like that:
$res = array(); //create a new array
while ($rs = mysqli_fetch_array($rsd)) {
$res[] = (string)$rs['name']; //add results to array, casted as string
}
header('Content-type: application/json'); //add JSON headers (might work w/o)
echo json_encode($res); //output array as JSON
...that way you should have all results in one array like
['name1', 'name2', 'name3']
Your PHP is all wrong:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Should be:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
label is the default label field within an array row that is used by jqueryautocomplete (I believe). Also the return must be an array of arrays each array row representing a match.
You can make it more complicated by adding a value field for what to make the textbox to actually equal to by doing:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
$cname[]['value'] = $rs['id'];
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
Of course I don't think your actually wanting the break; I put this in because:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Denotes to me that you are actually returning a single row from your results. If you are not and are actually returning all results then take the break; out.
to handle a json answer from a php ajax call i customize the source function and handle the result myself this way:
$(function() {
$( "#materials" ).autocomplete({
source: function(request, response){
$.post("autocomplete.php", {
term: request.term
}, function(data){
if (data.length == 0) {
data.push({
label: "No result found",
});
}
response($.map(data, function(item){
return {
label: item.name,
value: item.name
}
}))
}, "json");
},
minLength: 2,
dataType : "json"});
});

Image not flashing

I have a PHP script that displays an image(according to the current time) and I want it to flash the image so I tried adding a script to do so but its some what not working. Please have a look. I would be thankful for your help. Thanks in advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body onload="startit();">
<?php
$hour = date('H', time()); // Returns the hours of the server time, from 0 to 23.
switch ($hour) {
case '0':
$img = '0.jpg';
break;
case '1':
$img = '0.jpg';
break;
// ... and so on...
default:
$img = '1.jpg';
}
?>
<img src="<?php echo $img; ?>" id="mydiv" />
<script language=javascript>
/*This script written by Chris Stahl*/
/*It may be used and modified by */
/*webmaster's for private use. */
function startit() {
window.setInterval("changecolor()",100);
}
function changecolor() {
var rndred=Math.floor(256*Math.random());
var rndgreen=Math.floor(256*Math.random());
var rndblue=Math.floor(256*Math.random());
var colorarray=[rndred, rndgreen, rndblue];
var hexcolor="#";
for(i=0;i<3;i++) {
hexcolor=hexcolor +""+ converttohex(Math.floor(colorarray[i]/16));
hexcolor=hexcolor +""+ converttohex(colorarray[i]%16);
}
document.getElementById("mydiv").style.color=hexcolor;
}
function converttohex(num) {
switch (num) {
case 10: return "A";
case 11: return "B";
case 12: return "C";
case 13: return "D";
case 14: return "E";
case 15: return "F";
default: return num;
}
}
</script>
</body>
</html>
This will work
http://jsfiddle.net/mplungjan/9Kdh5/
<body>
<div id="myDiv"><img src="http://rd.cas.de/tim/native/image.png" id="myImg" /></div>
</body>
<script type="text/javascript>
/* This script written by Chris Stahl */
/* It may be used and modified by */
/* webmaster's for private use. */
window.onload=function() {
window.setInterval(changecolor,100);
}
function changecolor() {
var rndred=Math.floor(256*Math.random());
var rndgreen=Math.floor(256*Math.random());
var rndblue=Math.floor(256*Math.random());
var colorarray=[rndred, rndgreen, rndblue];
var hexcolor="#";
for(i=0;i<3;i++) {
hexcolor=hexcolor +""+ converttohex(Math.floor(colorarray[i]/16));
hexcolor=hexcolor +""+ converttohex(colorarray[i]%16);
}
document.getElementById("myDiv").style.backgroundColor=hexcolor;
}
function converttohex(num) {
switch (num) {
case 10: return "A";
case 11: return "B";
case 12: return "C";
case 13: return "D";
case 14: return "E";
case 15: return "F";
default: return num;
}
}
</script>

Categories