Update a query value using javascript/php - javascript

I know that this might be answered already by someone, but all the answers I could find, are intended for people who already know what they are doing and they paste thousands of lines of code, so I want something more on a begginer's side.
I have a value that I want to update ever 15 seconds to show the most updated information from a mysql db. I managed to show the latest result every once you reload the webpage.
The code is the following (everything is on the same file index.php):
PHP part:
<?php
$link = mysql_connect('localhost', 'root', '');
$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1');
if (!$LastUpdate) {
die('Could not query:' . mysql_error());
}
HTML part:
<small id="result">Last Update: <?php echo mysql_result($LastUpdate, 0); ?></small>
Jscript part:
<script>
setInterval(function() {
var date='Last update: '+'<?php echo mysql_result($LastUpdate, 0); ?>';
document.getElementById("result").innerHTML = date;
}, 1000);
The script part is supposed to refresh the "result" div every 1000 milliseconds. The problem is that once the script is performed one time the value gotten from the query doesn't change, having to reload the page in order for it to refresh.

First off all. Client asks Server for Webpage -> The Server build your Page -> The Browser get the response and render your HTML page. So far so good. Your <?php echo mysql_result($LastUpdate, 0); ?> always has the same value. You have to make an AJAX call and please don't use mysql functions anymore. There are deprecated (https://secure.php.net/manual/de/function.mysql-connect.php). Use PDO instead and always escape your statements to prevent sql injections or use an ORM. Here is a quick and dirty solution:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script>
function ajaxCall() {
$.ajax({
url: "ajax.php",
dataType: "json"
}).done(function (data) {
$(this).addClass("done");
var date = 'Last update: ' + data.firstData.dateTime + ' - count: '+ data.secondData.count;
document.getElementById("result").innerHTML = date;
});
}
$(function () {
ajaxCall();
setInterval(ajaxCall, 1000);
});
</script>
</head>
<body>
<small id="result"></small>
</body>
</html>
ajax.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('testdatabase', $link);
$LastUpdate = mysql_query('SELECT dateTime FROM LastUpdate where id=1') or die(mysql_error());
$firstData = mysql_fetch_assoc($LastUpdate);
$count = mysql_query('SELECT COUNT(Name) AS count FROM users, LastUpdate WHERE lastConnection = dateTime') or die(mysql_error());
$secondData = mysql_fetch_assoc($count);
$returnValues = array(
'firstData' => $firstData,
'secondData' => $secondData
);
echo json_encode($returnValues);
response example (JSON)
{
"firstData": {
"dateTime": "2016-06-16 00:00:00"
},
"secondData": {
"count": "1"
}
}

Related

Auto reload div contents with data from separate page with jquery

I am trying to reload a page and retrieve data automatically after 10 seconds or preferably less than that. Please i tried so many codes and it didn't work.
Here is what i am using now...
// script //
<script>
$(document).ready(function(){
// setInterval(function() {
// $("#load_msgs").load("load.php");
// }, 10000);
//var updateInterval = setInterval(function() {
//$('#load_msgs').load('load.php?p=<?php echo $username; ?>');
//},1000);
//});
var autoLoad = setInterval(
function ()
{
$('#load_msgs').load('load.php').fadeIn("slow");
}, 10000);
});
</script>
// php / html div id panel
<div class = 'container me' id = "load_msgs"> </div>
// php load.php file
<?php
include('config.php');
include('func.php');
//$username = $_GET['q'];
$o = "--DATABASE QUERY--";
$z = mysql_query($o) or die(mysql_error());
while ($roow = mysql_fetch_array($z)) {
$date = $roow['date'];
echo $roow['message']. " <span class = 'lil'>" . time_elapsed_string($date)."</span> \n <br />";
}
?>
I'm assuming from your comments that you can navigate directly to load.php and the data is echo'd. If that is the case, here's how I would set it up:
(It's not clear if you trying to load a file every X seconds, or just once after X seconds, Here is an example of both)
index.php:
<?php
$username='someUser'
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Load From PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var username = encodeURI( <?php echo isset($username) ? "'".$username."'" : ''; ?> );
$(function(){
var url='load.php?username='+username;
// load once after 2 seconds
setTimeout(function(){ $.get(url, function(response){ $('#load_msgs').html(response); } ); }, 2000);
// load every 2 seconds
setInterval(function(){ $.get(url, function(response){ $('#load_msgs_repeat').append(response+'<br>'); } ); }, 2000);
});
</script>
</head>
<body>
<h4>Div loaded once</h4>
<div id="load_msgs"></div>
<br>
<h4>Div loaded every 2 seconds</h4>
<div id="load_msgs_repeat"></div>
</body>
</html>
load.php:
<?php
$username= isset($_GET['username']) ? $_GET['username'] : null;
echo $username ? 'here is some data loaded from load.php for user: '.$username : 'here is some data loaded from load.php, but no user was provided' ;
?>
Here is a functioning example
The problem may be in config.php or func.php. Are you connecting to the database before running your query?
Add these two lines to the start of load.php:
ini_set("display_errors", "On");
error_reporting(E_ALL);
Then visit load.php in your browser. You should get some helpful error messages.
window.setTimeout(function(){window.location.replace("page.php")},5000);

Search database while I enter data in to a text area

I have a table data [Columns: id,question,answer each question have answer]; In frontend/UI i have a textarea while i paste a question to this field which search for exact question in db and show the result.
I want ajax no need to click any search button. I want this to work when I paste question in to the text area.
Code i am using
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS3</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>PHP5</h1>
<form class="form-inline">
<div class="form-group">
<input size="100" type="text" id="searchid" class="form-control" rows="10" cols="100" />
</div>
<div id="resultdiv"></div>
</form>
</div>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
</body>
</html>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#searchid').keydown(function (e){ // Event for enter keydown.
if(e.keyCode == 13){
var idvalue = $("#searchid").val(); // Input value.
$.ajax({ //Ajax call.
type: "GET",
url: "search.php",
data: 'id=' + idvalue ,
type: 'json',
success: function(msg){
// Show results in textareas.
msg = JSON.parse( msg ); // Line added
alert (msg);
$('#resultdiv').val(msg.answer);
}
}); // Ajax Call
} //If statement
}); //document.ready
</script>
My Search.php
<?php
if ($_GET['id']):
$dataid = json_decode($_GET['id']);
// Connect to database.
$con = mysqli_connect("localhost","root","");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
$sql = "SELECT answer FROM exam_css3 where question LIKE '$dataid' ";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
?>
This code is not working, can anyone help on this?
There are, among other things, some issues in your PHP.
First of all you search for $dataid, which means an exact match. You need to do
"SELECT answer FROM exam_css3 where question LIKE '%{$dataid}' ";
Then you always save only one answer, and you do not specify quote marks around 'answer', which might cause a PHP warning, which would corrupt the JSON output:
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
So you might want to rewrite that as
<?php
if (array_key_exists('id', $_GET)) {
$dataid = json_decode($_GET['id']);
// Here it would be good to check whether the decoding succeeded.
// I'd also try doing in HTML: data: { id: idvalue }
// Connect to database.
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
// Only interested in one match.
$sql = "SELECT answer FROM exam_css3 where question LIKE '%{$dataid}%' LIMIT 1";
$result = mysqli_query($con,$sql);
$answer = mysqli_fetch_assoc($result);
if (null === $answer) {
$answer = array('answer' => 'nothing found', 'status' => 'error');
}
// Since we're putting this into HTML...
$answer['answer'] = HTMLspecialChars($answer['answer']);
} else {
$answer = array('answer' => 'no query was supplied', 'status' => 'error');
}
Header ('Content-Type: application/json');
die(json_encode($answer));
In the code above I have added a 'status' variable so that in the jQuery you can do
if (msg.error) {
alert("Error: " + msg.answer);
return;
}
and further differentiate between correct and incorrect answers.
Other issues exist (for example you ought to use PDO and switch to prepared queries; as things stand, if the question contains a quote sign such as
What's a SQL injection?
your SQL search would throw an error. This is not limited to SQL injection. NO QUERY CONTAINING QUOTE MARKS WILL WORK. You need at least to escape the string dataid before placing it in the query.
You are defining twice the type in your ajax. json is the dataType not simple the type. type is get, what you do not need to set, that is the default.
The second problem is, you pass your data as a string, not as a json object, so on your server side, that will be an array, what you can not json_decode.

Trying to refresh JavaScript variable that is assigned to a PHP variable

I have assigned two variables that are equal to a PHP variable that can change at any time. I am trying to update a div every 5 seconds; for example, to update the number. I am assuming this doesn't work because the PHP doesn't run again once the page has loaded. What is the best way to get around this? I don't mind linking to another page if necessary. Here's my code:
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
});
Yeah - that won't work as you know.
setInterval(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, 5000);
That is a javascript + php. The browser runs javascript and php runs on the server. They run at different times and are mutually exclusive. The work apart from each other.
What you want to do (probably) if you are trying to update realtime is to use an ajax call.
http://api.jquery.com/jquery.ajax/
I find the api documentation good for reference but bad for example.
var jqXHR = $.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
}).done(function (data, status, jqXHR) {
$("#container").html(data);
alert("Promise success callback.");
}).fail(function (jqXHR,status,err) {
alert("Promise error callback.");
}).always(function () {
alert("Promise completion callback.");
})
That makes a pretty good example. Google "jqXHR" for other working examples
$(document).ready(function() {
var buyprice = <?php echo $coinTicker->price($coin2[1] , 'buy'); ?>;
var sellprice = <?php echo $coinTicker->price($coin2[1] , 'sell'); ?>;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
setInterval(function() {
$.get('/get_prices.php', function( data ) {
buyprice = data.buy;
sellprice = data.sell;
$('#currentbuyprice').html(buyprice);
$('#currentsellprice').html(sellprice);
}, "json" );
}, 5000);
});
And in your backend (/get_prices.php in this example, change it!)
<?php
$buy = 1;
$sell = 1;
echo json_encode(array(
'buy' => $buy,
'sell' => $sell,
));
exit;
You can make a simple ajax get request to a seperate php file that returns the data as json:
setInterval(function() {
$.get('/prices.php', function(data){
$('#currentbuyprice').html(data.buyprice);
$('#currentsellprice').html(data.sellprice);
});
}, 5000);
prices.php:
//code that creates $cointTicker and $coin vars goes here
header('Content-Type: application/json');
echo json_encode(
[
'buyprice' => $coinTicker->price($coin2[1] , 'buy'),
'sellprice' => $coinTicker->price($coin2[1] , 'sell')
]
);
You can't update static PHP variables, because the PHP-script gets an request, works and answers to the client, so the session is closed. The are two ways to handle that.
Way 1:
You have to connect your PHP to an Database. So you will send a request to a PHP-file, which updates the numbers in the database, so the values will be safed, also for the next request.
Way2:
You can make PHP Sessions php.net link. So you will save your values temporary in a session. That session will deleted after a while, and maybe that is not that, what you need. sessions are similar to cookies.
Both ways work through an AJAX-Request. So you need an Javascript-Function, that will send your request to that PHP-file, which will update the Database or the Session. You should also have a function to get that values from the Database or the Session.
Using the same approach (making a polling) you can make an ajax query
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<meta charset="utf-8" />
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js" charset="UTF-8"></script>
</head>
<body>
<script>
function send(){
$.ajax({
url: "a.php/",
type: 'GET',
success: function(res) {
var myVars = JSON.parse(res);
console.log(myVars[0].buyprice);
$('#currentbuyprice').html(myVars[0].buyprice);
$('#currentsellprice').html(myVars[0].sellprice);
}
});
}
setInterval(function(){ send() }, 3000);
</script>
currentsellprice:
<div id="currentbuyprice">
</div>
currentsellprice:
<div id="currentsellprice">
</div>
</body>
here the minimal part of the server
<?php
$out = "[";
$out .= '{"buyprice":"'. time(). '",';
$out .= '"sellprice":"'. time()/2 . '"}';
$out .="]";
echo $out;
?>
You can find a lot of information related with this topics (ajax and json) in internet.

AJAX cannot print elements onclick

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

JSON feed from MySQL works, but not with more than x records

I'm trying to get FullCalendar to work with my MySQL db. This works when I limit my query to 25 records. When I change my sql query to limit to, lets say 35 records, Fullcalendar will not add any event and basically keeps loading.
I checked with firebug what the JSON response was and in both times it's complete.
At first I thought the problem was the SQL query. The DB is 5000+ records long but the JSON response is loading in less then 200ms.
I'm using the demo json.html file for testing. will post the function here:
<script type='text/javascript'>
$(document).ready(function() {
$('#calendar').fullCalendar({
editable: true,
events: "json-events.php",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
</script>
This is my json-events.php
<?php
$conn = mysql_connect("") or die ("Unable to connect to MySQL server.");
$Exec = mysql_query("select Brand, date_in from planning ORDER BY date_in Desc Limit 35",$conn) or die(mysql_error());
mysql_close();
$events = array();
while($row = mysql_fetch_assoc($Exec)) {
$eventArray['title'] = $row['Brand'];
$eventArray['start'] = $row['date_in'];
$eventsArray['allDay'] = "";
$events[] = $eventArray;
}
header('Content-type: application/json');
echo json_encode($events);
?>
This is the JSON response:
[{"title":"Volkswagen Passat","start":"2011-04-28"},{"title":"Seat Alhambra","start":"2011-04-28"},{"title":"Ford Focus","start":"2011-04-20"},{"title":"BMW 5-Serie","start":"2011-04-20"},{"title":"Ford Mondeo","start":"2011-04-20"},{"title":"Volkswagen Caddy","start":"2011-04-20"},{"title":"Opel Zafira","start":"2011-04-18"},{"title":"Mazda 3","start":"2011-04-14"},{"title":"Opel Vectra","start":"2011-04-14"},{"title":"Peugeot 207","start":"2011-04-14"},{"title":"Volkswagen Golf","start":"2011-04-14"},{"title":"Volvo V90","start":"2011-04-14"},{"title":"Volvo V50","start":"2011-04-14"},{"title":"Volkswagen Polo","start":"2011-04-14"},{"title":"Volkswagen Golf","start":"2011-04-14"},{"title":"Ford Mondeo","start":"2011-04-14"},{"title":"Audi ","start":"2011-04-14"},{"title":"BMW 525i","start":"2011-04-14"},{"title":"Renault Laguna","start":"2011-04-14"},{"title":"Opel Astra","start":"2011-04-14"},{"title":"Seat Alambhra","start":"2011-04-14"},{"title":"Peugeot 307","start":"2011-04-13"},{"title":"Hyundai Atos","start":"2011-04-13"},{"title":"Citroen Xsara Picasso","start":"2011-04-13"},{"title":"Opel Astra","start":"2011-04-13"},{"title":"Volkswagen Golf","start":"2011-04-13"},{"title":"Peugeot 307","start":"2011-04-13"},{"title":"Volkswagen Passat","start":"2011-04-13"},{"title":null,"start":"2011-04-13"},{"title":"Citroen C1","start":"2011-04-13"},{"title":"Toyota Camry","start":"2011-04-13"},{"title":"Toyota Aygo","start":"2011-04-13"},{"title":"Nissan Qashqai","start":"2011-04-13"},{"title":"BMW 3 touring","start":"2011-04-12"},{"title":"Toyota Prius","start":"2011-04-12"}]
I tried everything I could come up with, I've spend 5 hours trying to make this work.
Is there anyone who has any idea how to make this work?
It looks like the error is in your database.
In your JSON feed you have an entry that is
{"title":null,"start":"2011-04-13"}
That null is probably what is holding you up.
I think i found part of the problem, special characters in the name turn up as NULLS in the JSON output, names like Renault Mégane. so i changed the charset to:
<meta http-equiv="Content-Type" content="text/html; charset="Latin-1"></meta>
I also changed the JSON and added:
mysql_set_charset("utf8");
The're still some minor issues, but it works! thanks for your help!

Categories