I was trying to create a notifications system for a website with the following code :
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
And the notifications.php :
$userid = $_SESSION[username];
$notifications = array();
$sql = "SELECT appreciation FROM ms_notifications WHERE email = '$userid' AND new = '1'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res)) {
while ($r = mysql_fetch_object($res)) {
$notifications[] = $r->appreciation;
}
$nb_result = mysql_num_rows($res);
}
$sql = "UPDATE ms_notifications SET new = '0' WHERE email = '$userid'";
mysql_query($sql) or die(mysql_error());
echo $nb_result;
Problem is that, as I'm new to jquery/Js, I don't know how to put the result inside of a div. For now it stays on the top of the page, above everything.
I tried that, inside the data function but not working... :
$('#test_app').html(data);
I guess it's a very stupid question but help would be really appreciated ! Thank you very much.
UPDATE : Here the HTML Code
<?php
session_start();
include ('connection/database.php');
include ('login_script.php');
include ('notifications.php');
if($logged_in){
?>
<!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>My Home</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="ms.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/font_i/specimen_files/easytabs.js" type="text/javascript" charset="utf-8"></script>
<!-- FONT SCRIPT-->
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#container').easyTabs({defaultContent:1});
});
</script>
<script type="text/javascript" charset="utf-8">
var scrollSpeed = 70; // Speed in milliseconds
var step = 1; // How many pixels to move per step
var current = 0; // The current pixel row
var imageHeight = 505; // Background image height
var headerHeight = 59; // How tall the header is.
//The pixel row where to start a new loop
var restartPosition = -(imageHeight - headerHeight);
function scrollBg(){
//Go to next pixel row.
current -= step;
//If at the end of the image, then go to the top.
if (current == restartPosition){
current = 0;
}
//Set the CSS of the header.
$('#main_logo').css("background-position","0 "+current+"px");
}
//Calls the scrolling function repeatedly
var init = setInterval("scrollBg()", scrollSpeed)
</script>
<!-- NOTIFICATIONS_SCRIPT !!!!!! -->
<script type="text/javascript" charset="utf-8">
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
</script>
<style>
body{
font-family:SommetRoundedLight;
}
</style>
</head>
<body>
<div id="container">
<div id="header_contain">
<div id="test_app">
</div>
</div>
</div>
</body>
</html>
<?php }
else{
echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("connexion.php");
-->
</script>';
} ?>
Thanks again
Use .append() instead of .html()
Instead of
$('#test_app').html(data);
just use:
$('#test_app').html('<div>' + data + '</div>');
Seems to simple to be it. Am I missing something?
Related
I'm have a problem. I want connect PHP and PostgreSQL, but don't know how.
HTML:
<?php
?>
<!DOCTYPE html>
<html lang = "pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Título -->
<title>test</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Font-Awesome CSS -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- Ubicua-cloud CSS -->
</head>
<body>
<form action = "" name = "f1" method = "post" style = "">
<input type = "text" id = "telefone">
<button type = "button" id = "init">iniciar sessão</button>
</form>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="js/bootstrap.min.js"></script>
<!-- Ubicua-cloud-js -->
<script src="login.js"></script>
</body>
</html>
DB connect:
<?php
$connect=pg_connect ("host=localhost dbname=test port=5432 user=postgres password=28974220")or
die("Error");
?>
JS to catch user informations:
$(document).ready(function(){
$('#init').click(function(){
var telefone=$('#telefone').val();
alert(telefone);
$.ajax({
type:"POST",
dataType:'json',
url:'login.Ajax.php',
data:{telefone:telefone},
success: function(response){
if(response.resposta==true){
$('#msg').html(response.msg);
window.location='test.php';
}
else{
$('#msg').html(response.msg);
}
},error:function(){
alert('error');
}
});
});
});
The PHP code to validate informations:
<?php
include_once('includes/connect.php');
$msg_ok=false;
$msg_error='O sistema está indisponível.';
if(isset($_POST['telefone']))
if($_POST['telefone']!="")
$telefone=$_POST['telefone'];
$consulta=pg_query($connect, ("Select * from test where telefone='$telefone"));
if(pg_num_rows($consulta)>0)
$msg_ok=true;
$usua=pg_fetch_array($consulta);
session_start();
$_SESSION['id']=$usua[0];
$_SESSION['telefone']=$usua[1];
$msg_error='Logado';
else
$msg_error='Telefone não existe.';
endif;
else
$msg_error='Telefone incorreto.';
endif
else
$msg_error='Erro.';
endif;
$saidaJson=array('resposta' => $msg_ok, 'msg' => msg_error);
echo json_encode($saidaJson);
?>
I received error messages to catch user informations, help, please.
I'm assuming you are using PDO. If so, you need make changes to the database connection file(substitute the variables with your database values):
<?php
$db = new PDO("pgsql:dbname=$dbname;host=$host";port=$port, $dbuser, $dbpass);
?>
I solved the problem, but now I'm needing exchange informations between the php and js...I have a script that simulates a person typing and need it to talk to users calling them by their proper names, but I don't know how, I need concatenate one variable in JS, but before that I need store one PHP variable in one JS variable.
var init = document.getElementById('init_text');
var init_text = 'Hi <nome>, I'm your friend!';
function digit(str, el) {
var char = str.split('').reverse();
var typer = setInterval(function () {
if (!char.length) return clearInterval(typer);
var next = char.pop();
el.innerHTML += next;
}, 60);
}
digit(init_text, init);
I'm unable to get one of my functions to work. My assumption is that there is a 'scope' issue due to the fact the function works when used in the same file it modifies. Anyway here is the function and fiddle.
The function as the title suggests should replace text on hover and 'off-hover' put the original text back. The code snippet below works, but when used as I'm trying to(fiddle) it does not work.
http://jsfiddle.net/s4q8bva6/3/
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
01 - System Overview and System Manager
<script>
$("a.open").hover(
function() {
var $this = $(this);
$this.data('initialText', $this.text());
$this.text("Click to return to previous page");
},
function() {
var $this = $(this); // caching $(this)
$this.text($this.data('initialText'));
}
);
</script>
</body>
</html>
EDITS:Update
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP File Tree Demo</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link href="styles/default/default.css" rel="stylesheet" type="text/css" media="screen" />
<!-- Makes the file tree(s) expand/collapsae dynamically -->
<script src="php_file_tree.js" type="text/javascript"></script>
<script src="jquery-1.11.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<h1>File Tree </h1>
<h2>Browsing Training Videos...</h2>
<?php
//This links the user to http://example.com/?file=filename.ext
//echo php_file_tree('Training/', "http://example.com/?file=[link]/");
include("php_file_tree.php");
// This links the user to http://example.com/?file=filename.ext and only shows image files
$allowed_extensions = array("htm");
echo php_file_tree("Training/", "http://URL/files/[link]", $allowed_extensions);
echo "This is a TEST";
// This displays a JavaScript alert stating which file the user clicked on
//echo php_file_tree("demo/", "javascript:alert('You clicked on [link]');");
?>
<!-- This function collapses the li under an open li-->
<!-- Togles all 'Other' Top Level il elements on click-->
<script>
$(document).ready(function () {
var col = 2
$(".pft-directory").click(function () {
$(".pft-directory").toggle("fast");
$(this).toggle("fast");
if (col > 1) {
$(".php-file-tree").css("columns", "1", "-webkit-columns", "1");
col = 1;
} else {
$(".php-file-tree").css("columns", "2", "-webkit-columns", "2");
col = 2;
}
});
$(".open").hover(function () {
var $this = $(this);
$this.data('initial-text', $this.text());
$this.text("Click to return to previous page");
},
function () {
var $this = $(this); // caching $(this)
$this.text($this.data('initial-text'));
});
});
</script>
</body>
</html>
I am pulling data from a mySql database using php to plot a graph using flot. The query works fine but no graph is being displayed when I run the code. A blank space is coming up where the graph should be. Here is what I have:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Graph</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<script language="javascript" type="text/javascript" src="../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../jquery.flot.js"></script>
</head>
<body>
<h1>Flot Graph</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$mysqli=new mysqli('localhost','root',"",'simpledb');
$sql="select name, age from `people` where age=23";
$results = $mysqli->query($sql);
if ($results)
{
while ($row=$results->fetch_assoc())
{
$dataset1[] = array($row['name'],$row['age']);
}
}
else
{
echo "Error";
}
?>
<script type="text/javascript">
var dataset1 = <?php echo json_encode($dataset1); ?>;
$(function ()
{
$.plot($("#placeholder"), [
{
data: dataset1,
bars: {show: true}
}
]);
});
</script>
</body>
</html>
It looks like your x values are strings, yet you haven't included the categories plugin.
Thanks everyone. I got it to work. I'm not sure what the problem was but it worked after I changed the javascript part to :
$(function ()
{
$.plot("#placeholder", [ dataset1 ], {
series: {
bars: {
show:true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength:0
}
});
});
I have a problem using flot to plot data from a database.
using json_encode in php I have tried to get the plot data but I have been unsuccessful.
Below is my code, kindly assist
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>`enter code here`
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="./flot/layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
</head>
<body>
<h1>Database Plotting</h1>
<div id="placeholder" style="width:600px;height:300px;"></div>
<?php
$server = "localhost";
$user="user";
$password="password";
$database = "database";
$connection = mysql_connect($server,$user,$password);
$db = mysql_select_db($database,$connection);
$query = "SELECT x_value, y_value FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$dataset1[] = array($row['x_value'],$row['y_value']);
}
?>
<script type="text/javascript">
$(function () {
var dataset1 = <?php echo json_encode($dataset1,); ?>;
$.plot($("#placeholder"),[dataset1] );
});
</script>
</body>
</html>
The ouput from the json-encode dataset1 is thus the following [["1380111342","0"],["1380111679","0"],["1380112099","20"],["1380112109","300"],["1380112114","40"],["1380112120","56"],["1380112127","36"],["1380112132","40"],["1380112138","78"]]
Try change this line:
$.plot($("#placeholder"), [dataset1] );
To that:
$.plot($("#placeholder"), [JSON.parse(dataset1)]);
var dataset1 = <?php echo json_encode($dataset1,); ?>;
Lose the comma after "$dataset1" and the semi-colon at the end.
This should work just fine:
var dataset1 = <?php echo json_encode($dataset1); ?>
I am new to jQuery. I am trying jQuery autocomplete remote data source here is my code:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta name="GENERATOR" content="Quanta Plus">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
</head>
<body>
<meta charset="utf-8">
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" value="" />
</div>
</div><!-- End demo -->
</body>
</html>
FILE: search.php
<?php
require_once("includes/connection.php");
$q = strtolower($_GET["birds"]);
echo $q;
$return = array();
$query = "SELECT title
FROM `project`
WHERE `title` LIKE CONVERT( _utf8 '%$q%'
USING latin1 )";
$resultset=mysql_query($query,$connection);
$json = '[';
$first = true;
while ($row = mysql_fetch_assoc($resultset)) {
if (!$first) {
$json .= ',';
} else {
$first = false;
}
$json .= '{"value":"'.$row['title'].'"}';
}
$json .= ']';
echo $json;
?>
getting the following error:
Notice:
Undefined
index: birds in /var/www/html/workbench/sudeepc/project/search.php
on line 4
[
{"value":"chandrayaan"},
{"value":"Project Management System"},
{"value":"shoping cart"},
{"value":"hospital management system"}
]
fire bug show the following error while searching on that text box and there is no suggestion for search.
How to resolve this problem?
As per the comments, it appears that the first error was caused by looking for the wrong $_GET variable. Props to you for spotting that with Firebug and correcting it appropriately.
The reason that it is not filling in a value currently is because of the extra string echoed in front of the JSON. Remove the line echo $q; and it should work.