JQuery Autocomplete with PDO Statements - javascript

I am having a hard time by finding this error. I spent around 10 hours searching and testing but google couldn't provide me anything. So you guys are my really last hope.
I have a simple html textfield:
<input type="text" value="" id="keyword" name="zip" placeholder="Please enter ZIP code" required>
and here is my Javascript code(the JQuery files are linked correctly, don't worry):
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "autocomplete", { keyword: keyword } )
.done(function( data ) {
console.log(data);
});
}
});
});
When I type in the textfield the value "sw" I get following result in the console:
["Swaziland\r","Sweden\r","Switzerland\r"]
Which should be correctly. Here's my first question. Are the "\r" normal?
And my second and more important question is: How do I add the query function autocomplete? My goal would be like the following example: https://jqueryui.com/autocomplete/
Please help me, I tested around for so long and I'm unable to find the solution. And I think its a little stupid error.
Here all the files:
autocomplete.php
if (!isset($_GET['keyword'])) {
die();
}
$keyword = $_GET['keyword'];
$data = SQL::searchForKeyword($keyword);
echo json_encode($data);
searchForKeyword function:
static function searchForKeyword($keyword) {
$stmt = self::getInstance()->_conn->prepare("SELECT NameCountry as countries FROM `country` WHERE NameCountry LIKE ? ORDER BY countries");
$keyword = $keyword . '%';
$stmt->bindParam(1, $keyword, PDO::PARAM_STR, 100);
$isQueryOk = $stmt->execute();
$results = array();
if ($isQueryOk) {
$results = $stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error executing statement.', E_USER_ERROR);
}
return $results;
}

The thing with jQuery ui documentation, is to find the right page.
What you need is the Remote jsonp datasource example.
I lost a lot of time on the remote datasource example (Wich I have not even been able to run), because I was affraid by the "p"...
So here is my version, a little enhanced, of an example to dynamically load the autocomplete dropdown.
I hope it will help lot of people.
The funny thing is that I didn't use jsonp like jQuery documentation suggests.
It creates a strange unclear error in console:
Error: jQuery112409377035747123055_1476875409950 was not called(…)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<style>
.ui-autocomplete-loading {
background: white url("ajax-loader.gif") right center no-repeat;
}
.ui-widget{
width:500px;
}
.ui-front{
width:10em;
background-color:#bebebe;
}
#log{
height: 200px;
width: 500px;
overflow: auto;
}
#noResult{
display:none;
color:red;
padding-left:1em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
function log( message ){
$( "<div>" ).text( message ).appendTo( "#log" );
$("#UScities").blur();
}
$( "#UScities" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
data: {keyword:request.term},
dataType: 'json', // DON'T use jsonp !
cache: false,
success: function(data){
console.log(data);
// Even on success, it may have no results...
if(typeof(data[0])!="undefined"){
// Remove the no result error in case it's displayed
$("#noResult").css("display","none");
// For fun, count it!
var count = 0;
while (data[count]) {
console.log(data[count]);
count++;
}
}else{
count = "NO";
// Display the no result error
$("#noResult").css("display","inline");
}
console.log(count+" RESULTS");
// Pass the data to the dropdown!
response(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
},
minLength: 4,
select: function( event, ui ) {
log( ui.item.value );
}
});
// Show results on input focus
$("#UScities").on("focus",function(){
$("#ui-id-1").css("display","block");
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="UScities">USA cities: </label>
<input type="text" id="UScities"><span id="noResult">No Result</span><br>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
<div id="log" class="ui-widget-content"></div>
</div>
</body>
</html>
I've added the result count in console (which could be used to trigger something) and a "NO RESULT" message to user, because it is possible to get no result on a keyword search.
Now, what is lacking terribly in the jQuery documentation, is how to produce a json output.
<?php
if (!isset($_GET['keyword'])) {
// Do nothing if no keyword!
die();
}
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[Database Name];host=localhost';
$user = '[Database User]';
$password = '[UserPassword]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
// Getting the keyword and add % to get data that begins with it.
$keyword = $_GET['keyword'] . '%';
// If you want the keyword to be "contained" in the data, use (uncomment it):
//$keyword = '%' . $_GET['keyword'] . '%';
// Query.
$query = "SELECT city FROM SO_USAzipcodes WHERE city LIKE ? GROUP BY city limit 30";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $keyword);
// Executing.
$stmt->execute();
// If SQL error...
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die();
}
// Fetching.
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
// This is sending the json to autocomplete.
echo json_encode( $data );
?>
If you have a syntax error in this file...
Or if there is an error due to DB connection or a SQL syntax error...
You will get something like this in console:
SyntaxError: Unexpected token < in JSON at position 0(…)
And nothing happens in the main page, but the rotating .gif that keeps on turning. By the way, I just discovered this loading gif generator that worth seeing. ;)

Related

AJAX - try to implement live search with debounce

I tried to implement AJAX live search with AJAX and I did it quite well. Then I tried to add the _.debounce function so it will not overloads the server but it didn't work well..
this is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", _.debounce(function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
}),250);
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</body>
</html>
and this is the php file:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);
if(isset($query)){
// Attempt select query execution
$sql = "SELECT * FROM countries WHERE name LIKE '" . $query . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found for <b>$query</b></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
Thanks!
Your code doesn't include the Underscore library, so _.debounce() won't be available to use. That said, you can achieve what that method does quite easily by using a setTimeout() call:
var timeout;
$('.search-box input[type="text"]').on("keyup input", function() {
var term = $(this).val();
var $resultDropdown = $(this).siblings(".result");
clearTimeout(timeout);
timeout = setTimeout(function() {
if (term.trim().length) {
$.get("backend-search.php", { query: term }).done(function(data) {
$resultDropdown.html(data);
});
} else {
$resultDropdown.empty();
}
}, 250);
});
you can do this by setting a setTimeout to make an ajax call on every change that occurs on input after passing a specific time but don't forget to kill the previous calls. you can use the code below to any function needs denounce.
var debounce;
$('#input').on('input', function (e) {
clearTimeout(debounce);
debounce = setTimeout(
function () {
searchText(e.target.value)
}, 1000
);
});

Update a query value using javascript/php

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"
}
}

PHP ajax search results in mucking up my page

Hi guys its my first time trying out a live ajax search for my site. I am new to php so any help on this matter would be great. I was following some tutorials here and there and trying to make it work, but every time i press search no results come up at all. Any help on this matter would be great.
Code:
<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'");
while(($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>',$row['ingName'],'</li>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<input type="text" class="searchFunction"> <input type = "submit" value ="Search">
<div class = "dropdown">
<ul class = "result">
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.searchFunction').keyup(function() {
var search_term = $(this) .attr('value');
$.post('build.php', {search_term:search_term}, function(data) {
$('.result').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value);
$('.result').html('');
});
});
});
});
</script>
</body>
</html>
Again i am so new to this, so i am just trying to build my knowledge around this area. Any help in solving this big problem out would be great
P.S i know about the sql injections :) but one step at a time for now x
As has been pointed out - the method used so far is at risk of sql injection so before getting committed to using the now deprecated mysql suite of functions you would be wise to read up on and implement mysqli which, when you employ prepared statements will offer significant protection from malevolent sql injection attacks.
As your ajax query is being sent to the same page ( by the looks of code posted ) one important thing to do is exit from the phpafter sending the response - otherwise you end up sending the entire page ( which would also be badly formed as there would be content outside the html tags ) and I suspect this is not your desired goal.
The ajax function looks, to my untrained eye, ok but as I don't use jQuery I might well be wrong and have missed something important.
<?php
/*
as the rest of the page doesn't use a db connection,
only load the db conn if the page is requested via post
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* assign db connection to a variable */
$conn=mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
/* empty() does an implied `isset` */
if ( !empty( $_POST['search_term'] ) ) {
$search_term = mysql_real_escape_string( $_POST['search_term'] );
/*
You ought to look at using mysqli ( prepared statements )
rather than the now deprecated `mysql_*` functions
*/
$query = mysql_query( "SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'", $conn );
if( $query ){/* only send response if the query succeeds */
while( $row = mysql_fetch_assoc( $query ) ) {
echo '<li>',$row['ingName'],'</li>';
}
}
}
mysql_close( $conn );
/* make sure that the rest of the page is not sent back with the response data */
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gotta have a title!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
/* I could not get this to work - I don't know what this is doing as I don't use jQuery */
/*var search_term = $(this).attr('value');*/
/* this however does work */
var el=event.target || event.srcElement;
var search_term=el.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 2 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class="container">
<input type="text" name='search_term' class="searchFunction">
<input type="submit" value="Search">
<div class="dropdown">
<ul class="result"></ul>
</div>
</div>
</body>
</html>
Full, working example
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if ( !empty( $_POST['search_term'] ) ) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* using lower() helped account for vagueries in spelling */
$sql='select * from `maps` where
lower( `location_name` ) like lower( "%'.$_POST['search_term'].'%" );';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
echo "<li>".$rs->location_name."</li>";
}
}
}
exit();
}
?>
<!doctype html>
<html lang='en'>
<head>
<title>Gotta have a title!</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript'>
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
var search_term=this.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 5 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr( 'value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class='container'>
<input type='text' name='search_term' class='searchFunction'>
<input type='submit' value='Search'>
<div class='dropdown'>
<ul class='result'></ul>
</div>
</div>
</body>
</html>
You can try writing your query without the quotations ie:
$query = mysql_query("SELECT ingName FROM ing WHERE ingName LIKE '$search_term%'");
and you can also loosen your search by using '%$search_term%' instead of '$search_term'.
Another possible issue is the mysql_connect(). I was using that function and it did not work for me so I resolved to the mysqli_connect() function which worked for me.
Some more advise, you do not need the ==true and you can also you can use
!empty($_POST['search_term']).
Once you are through learning that you can also try the PDO function which is far much better than initiating your own connection.
You initiate a PDO connection like this.
$dbh1 = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'dbpass');
Then you can search like this. - using the initialized connection.
$query = "SELECT ingName from ing WHERE ingName LIKE %$search_term%";
$stmt = $dbh1->prepare($query);
$stmt->execute();
$allRows = count($stmt);
$row = $stmt->fetch(PDO::fetch_assoc);
foreach($row as $one){
echo "<li>".$one['ingName']."</li><br>";
}
Cheers!

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.

Categories