How to run an autocomplete on an array with PHP, MySQL, jQuery? - javascript

I need to extract saved information from a database table with the autocomplete function on "N" number of entries. That is, in each entry of a new row, insert a new data and continue repeating said function (autocomplete).
Example: The information contained in the variable availableTags and availableTags2 is the information I want to extract from the database table.
What would the command for such a function look like?
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
$( function() {
var availableTags2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"];
var availableTags = ["ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskel","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme", "MySQL", "PostgreSQL"];
$( ".tags" ).autocomplete({
source: 'pl.php',
select: function (event, ui) {
var index = availableTags.indexOf(ui.item.value);
$("#" + $(event.target).attr("data-target")).val(availableTags2[index]);
}
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags:</label>
<input class="tags" data-target="code1" name="name">
<label for="tags">Number:</label>
<input name="code" id="code1"><br><br>
<label for="tags">Tags:</label>
<input class="tags" data-target="code2" name="name">
<label for="tags">Number:</label>
<input name="code" id="code2"><br><br>
<label for="tags">Tags:</label>
<input class="tags" data-target="code3" name="name">
<label for="tags">Number:</label>
<input name="code" id="code3"><br><br>
</div>
</body>
</html>
pl.php
<?php
if (isset($_GET['term'])){
# conectare la base de datos
include('./dbcontroller.php');
$db_handle = new DBController();
$return_arr = array();
$sqlc = "SELECT * FROM pl WHERE availableTags like '%".$_GET['term']."%' LIMIT 5";
$faq = $db_handle->runQuery($sqlc);
foreach($faq as $k=>$v) {
/* Recuperar y almacenar en conjunto los resultados de la consulta.*/
$row_array['value'] = $faq[$k]['availableTags'];
$row_array['availableTags']=$faq[$k]['availableTags'];
$row_array['availableTags']=$faq[$k]['availableTags'];
$row_array['availableTags2']=$faq[$k]['availableTags2'];
array_push($return_arr,$row_array);
}
/* Codifica el resultado del array en JSON. */
echo json_encode($return_arr);
}
?>
dbcontroller.php
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "";
private $database = "programming languages";
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_array($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function insertQuery($query) {
mysqli_query($this->conn, $query);
$insert_id = mysqli_insert_id($this->conn);
return $insert_id;
}
function getIds($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_array($result)) {
$resultset[] = $row[0];
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn, $query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
}
?>
programming languages.sql
-- phpMyAdmin SQL Dump
-- version 5.2.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 29-01-2023 a las 17:54:32
-- Versión del servidor: 10.4.25-MariaDB
-- Versión de PHP: 8.1.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET #OLD_CHARACTER_SET_CLIENT=##CHARACTER_SET_CLIENT */;
/*!40101 SET #OLD_CHARACTER_SET_RESULTS=##CHARACTER_SET_RESULTS */;
/*!40101 SET #OLD_COLLATION_CONNECTION=##COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `programming languages`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `pl`
--
CREATE TABLE `pl` (
`availableTags` varchar(250) NOT NULL,
`availableTags2` int(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Volcado de datos para la tabla `pl`
--
INSERT INTO `pl` (`availableTags`, `availableTags2`) VALUES
('ActionScript', 1),
('AppleScript', 2),
('Asp', 3),
('BASIC', 4),
('C', 5),
('C++', 6),
('Clojure', 7),
('Cobol', 8),
('ColdFusion', 9),
('Erlang', 10),
('Fortran', 11),
('Groovy', 12),
('Haskel', 13),
('Java', 14),
('JavaScript', 15),
('Lisp', 16),
('Pearl', 17),
('PHP', 18),
('Python', 19),
('Ruby', 20),
('Scala', 21),
('Scheme', 22),
('MySQL', 23),
('PostgreSQL', 24);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=#OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=#OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=#OLD_COLLATION_CONNECTION */;
Thanks.
HERE MY PROBLEM
When I extract the data from the variables availableTags and availableTags2 in input, the corresponding number does not appear, only the name of the programming language.

Related

php pdo charset utf8 mysql : unable to find an accentuated field

I have got a table 'famille'
CREATE TABLE famille (
idf INTEGER(6) NOT NULL ,
>>>>>> nomf VARCHAR(40) NOT NULL,
CONSTRAINT pk_famille
PRIMARY KEY (idf),
>>>>>> CONSTRAINT un_famille_nomf
>>>>>> UNIQUE (nomf)
)ENGINE = InnoDB, DEFAULT CHARACTER SET utf8; <<<<<<<<<
When adding a new 'famille', i have to check constraints : the unique constraint refer to a text field.
Examples :
idf nomf
100 Actinidiacées
110 Aizoaceae
120 Amaranthacées
130 Amaryllidacées (Liliacées)
140 Apiacées (Ombellifères)
...
I use asynchronous query Javascript/Php to check values in a form that enable to add a new 'famille' and that the value of the field 'fnom' in the form already exists in the table : when le input field is not accentuated, it works, but when there are accentuated characters, it does not work : the form is submit and I get a normal SQL error.
Form simplified :
<html><head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta charset="utf-8" /> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<title>Gestion - Administration du site</title>
...
<link rel='stylesheet' href='main.css' type='Text/css'>
<script src="js/checkfamille.js?dev=1574345195"></script>
</head>
<body><h2 class='entete'>Les familles</h2>
...
<form name='frmNewfamille' id='frmNewfamille' method='post' ><fieldset id='fs1'><legend><b>Informations</b></legend><div class='ligne'><span class='label'><label for='fidf'>Identifiant</label></span><span class='champs'>
<input type='number' size='6' minlength='6' maxlength='6' name='fidf' id='fidf' required value='' /></span>
</div><div class='ligne'><span class='label'><label for='fnomf'>Intitulé</label></span><span class='champs'>
<input type='text' size='40' minlength='40' maxlength='40' name='fnomf' id='fnomf' required value='' /></span></div></fieldset><fieldset>
<input type="hidden" id="valide" name="valide" hidden />
<input class='bouton' type='button' name='btnNewAfamille' id='btnNewAfamille' value='Ajouter'
onclick='return checkfamille();' />
>>>>>>>>>>>>>>>>>>>^^^^^^^^^^^
</fieldset>
</form>
...
Javascript :
function checkfamille()
{
var idf = document.forms["frmNewfamille"]["fidf"];
var nomf = document.forms["frmNewfamille"]["fnomf"];
// somme checks
...
// ajax call
...
return checkFamilleAjax('code.php?idf='+escape(idf.value)
+'&nomf='+escape(nomf.value) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+'&mode=insert');
...
function checkFamilleAjax(fichier, nom)
{
var xhr_object;
if(window.XMLHttpRequest) // FIREFOX
xhr_object = new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
else
return(false);
xhr_object.onreadystatechange = function() {
if (xhr_object.readyState == 4 && (xhr_object.status == 200 || xhr_object.status == 0)) {
var reponse = (xhr_object.responseText).replace(/\s/g, "");
if(reponse=="0") {
document.getElementById("valide").value = "true";
document.forms["frmNewfamille"].submit();
return true;
} else if(reponse=="1") {
// set error fields on the form
....
}
}
xhr_object.open("GET", fichier, true);
xhr_object.send(null);
}
PHP code :
<?php session_start();
// includes
...
$database = new Database();
$famille = new Famille($database);
try {
if ($mode == 'insert') {
if (isset($_GET["idf"]) && isset($_GET["nomf"])) {
// checks if number already exists
$database->query('SELECT idf FROM famille WHERE idf = :id;');
$database->bind(':id', $_GET["idf"]);
if ($result = $database->execute()) {
if ($database->rowCount() >0) {
echo "1"; exit;
}
} else {
echo "7 ". $database->getError(); exit;
}
// checks if name already exists
$database->query('SELECT idf FROM famille WHERE nomf = :lname;');
$database->bind(':lname', $_GET["nomf"]);
if ($result = $database->execute()) {
if ($database->rowCount() > 0) {
echo "2"; exit;
}
} else {
echo "8 ". $database->getError(); exit;
}
echo "0"; exit;
} else {
echo "9"; exit;
}
...
Here is the value of $_POST from my form :
Array ( [fidf] => 3214 [fnomf] => Rosacées [valide] => true )
and here is the query error :
Erreur SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate
entry 'Rosacées' for key 'un_famille_nomf'
I have checked
- all sources files : utf8 OK
- the database data
- php/mysql connexion parameters and code :
define("DB_HOST", "localhost");
define("DB_USER", "xxxx");
define("DB_PASS", "xxxx");
define("DB_NAME", "xxxx");
define("DB_CHARSET", "utf8");
and a database class :
class Database
{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $charset = DB_CHARSET;
private $dbh;
private $error;
private $stmt;
public function __construct(){
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname. ';charset=' . $this->charset;
// Options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
);
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
$this->dbh->exec("SET NAMES utf8;");
}
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
...
May be I miss something ?
Thanks for help.
****EDIT****
Just after writing this message, I wonder if it does not come from escape(nomf.value) in the call of PHP asynchronous php code... I remove 'escape' and that works !!!
return checkFamilleAjax('code.php?idf='+idf.value
+'&nomf='+nomf.value
+'&mode=insert');
Javascript 'escape' change characters (accuentuated for example) to hexadecimal value : (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape * change * from french to english reference)
escape("abc123"); // "abc123"
escape("äöü"); // "%E4%F6%FC"
escape("ć"); // "%u0107"
This function is obsolete and 'encodeURI' ou 'encodeURIComponent' should be use when necessary.

Why am I getting "InvalidValueError: not a LatLng or LatLngLiteral"?

Coding a delivery service Web App using Google Map API. Haven't had a problem until I started to use multi-dem array as LatLng Reference. Now I'm getting this weird error --
"InvalidValueError: not a LatLng or LatLngLiteral"
I used a similar array reference for LatLng earlier and no problem, but now that it's multi-dem array I got this weird error.
<?php
session_start();
require 'ConnectTest.php';
// IF YOU'RE NOT LOGGED IN, KICK BACK TO LOGIN SCREEN
if(!isset($_SESSION['username']) || !isset($_SESSION['password'])){
header("Location:signin.php");
}
$servername = "localhost:3306";
$user = "sonic_client";
$pass = "client";
$dbName = "sonicStrains";
$drop = "DROP TABLE ".$_SESSION['username']."_deliveries";
mysqli_query($server, $drop);
//CREATE INDIVIDUAL DRIVER TABLE TO HOLD DELIVERIES
$createQuery = "CREATE TABLE ".$_SESSION['username']."_deliveries (
transaction_id VARCHAR(13),
timePaid INT(11),
username VARCHAR(30),
user_location VARCHAR(255),
user_lat float(10,6),
user_long float(10,6),
item_name VARCHAR(20),
item_quantity float,
driver_username VARCHAR(60),
driver_lat float(10,6),
driver_long float(10,6),
on_delivery tinyint(1))";
$created = mysqli_query($server, $createQuery);
if ($created){
//query the deliveries for open deliveries up untill 5 deliveries
$queryString = "SELECT * FROM deliveries LIMIT 5";
$query = mysqli_query($server, $queryString);
if($query){
// CREATE ARRAY TO HOLD QUERY ROWS
$rows = array();
while($queryresult = mysqli_fetch_assoc($query)){
$rows[] = $queryresult;
}
echo floatval($rows[0]['user_lat']);
echo"<br>";
//INSERT & UPDATE THE TABLES WITH DELIVERY QUERIES
foreach($rows as $row){
// INSERT INTO INDIVIDUAL DRIVER TABLE
$insertQuery = "INSERT INTO ".$_SESSION['username']."_deliveries (transaction_id, user_location, user_lat, user_long) VALUES('$row[transaction_id]', '$row[user_location]', '$row[user_lat]', '$row[user_long]')";
$insertExec = mysqli_query($server, $insertQuery);
// UPDATE MASTER LIST OF DELIVERIES SO THAT OTHER DRIVERS DONT QUERY SAME ORDER
$updateQuery = "UPDATE deliveries SET on_delivery=true, driver_username='$_SESSION[username]' WHERE transaction_id='$row[transaction_id]'";
$updateExec = mysqli_query($server, $updateQuery);
}
}else{echo mysqli_error($server);}
}else{echo mysqli_error($server);}
if(isset($_GET['pop'])){
array_shift($rows);
echo print_r($rows);
}
echo<<<_
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div class="Banner">
<div class="TitleText">Sonic Strains ©</div>
</div>
<div class="login">Logout</div>
<div class="gallery" id="container">
<div class="map" id="mapInsert"></div>
<div class="navButton">Start Nav</div><div class="orderButton">Order Details</div>
<div class="abortButton">Abort</div><div class="confirmButton" onclick="shiftOrder()">Confirm</div><div class="disclaimer"></div>
</div>
<script>
function initMap() {
navigator.geolocation.getCurrentPosition(function(position) {
var initialLocation = {lat:$rows[0]['user_lat'], lng:$rows[0]['user_long']};
var Map = new google.maps.Map(document.getElementById('mapInsert'));
Map.setCenter(initialLocation);
Map.setZoom(13);
// MAKE ANOTHER MARKER FOR THE CLIENT LOCATION
var userLocation = {lat:$rows[0]['user_lat'], lng:$rows[0]['user_long']};
var marker = new google.maps.Marker({
position:userLocation,
map:Map,
draggable:false,
clickable:false
});
marker.setMap(Map);
}, function(positionError) {
alert('Location could not be found');
},{enableHighAccuracy:true, timeout: 3000, maximumAge:1000});
}
function shiftOrder(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
console.log(this.responseText);
}
http.open("GET", "driverIndex.php?pop='pop'", true);
http.send();
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]&callback=initMap"
async defer></script>
</body>
</html>
_;
?>
Here's a peek at one element of the ref array --
array(5) { [0]=> array(12) { ["transaction_id"]=> string(13) "5c2fb27078926" ["timePaid"]=> string(1) "0" ["username"]=> string(0) "" ["user_location"]=> string(44) "1301 Bataan St NW, Washington, DC 20036, USA" ["user_lat"]=> string(9) "38.907246" ["user_long"]=> string(10) "-77.037292" ["item_name"]=> string(18) "girl_scout_cookies" ["item_quantity"]=> string(1) "1" ["driver_username"]=> string(7) "Driver1" ["driver_lat"]=> string(8) "0.000000" ["driver_long"]=> string(8) "0.000000" ["on_delivery"]=> string(1) "1" }
Again, I've tried to parse the lat & long with floatval() because it says it's not a number
var initialLocation = {lat:floatval($rows[0]['user_lat']), lng:floatval($rows[0]['user_long'])};
but i get -- "floatval not defined"
The PHP variables aren't inside brackets --
var initialLocation = {lat:{$rows[0]['user_lat']}, lng:{$rows[0]['user_long']}};

Filling ammap using mysql

I'm not that experienced in Javascript and I'm kind of stuck with ammap (http://www.amcharts.com/javascript-maps/).
The idea is to add some locations to the map from a mysql database. Their tutorial chapter on this is outdated and recommends using the DataLoader plugin instead (http://www.amcharts.com/tutorials/using-data-loader-plugin/). This, however, is for amcharts rather than ammap, and I can't figure it out.
Here's the code:
index.php
<script src="ammap/ammap.js" type="text/javascript"></script>
<link rel="stylesheet" href="ammap/ammap.css" type="text/css"
media="all" />
<script src="ammap/maps/js/germanyLow.js" type="text/javascript"></script>
<script
src="http://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"
type="text/javascript"></script>
<script type="text/javascript">
AmCharts.makeChart( "mapdiv", {
"type": "map",
"dataProvider": {
"map": "germanyLow"
}
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true
},
} );
</script>
<div id="mapdiv" style="width: 600px; height: 400px;"></div>
data.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "map";
$conn = new mysqli ( $server, $user, $pass, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT latitude, longitude FROM map";
$result = $conn->query($sql);
if($result->num_rows > 0){
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}else{
//
}
$string = json_encode($data);
echo $string;
?>
The json string of the data.php file is:
[{"latitude":"48.47","longitude":"9.11"},{"latitude":"53.33","longitude":"10"}]
The map won't load with this code. If I comment out the dataLoader part, the map itself loads just fine. Does anybody know how to use the dataLoader properly? Any help would be greatly appreciated.
Solved with help from amcharts support crew. For those of you interested in the solution:
AmCharts.makeChart("mapdiv", {
"type": "map",
"data": {
"map": "germanyLow"
},
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true,
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
}
});

Calendar DayPilot "Cannot read property 'getTime' of undefined" when using a different Database

I am still a debutant in JavaScript/Json (I've never worked with Json) and I have a problem when trying to use DayPilot Calendar. (I am also French, so forgive my mistakes please).
http://code.daypilot.org/17910/html5-event-calendar-open-source
When I download sources and use it it works perfectly, but when I try to adapt it to my database, I can't make it work.
Source Code :
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Event Calendar</title>
<!-- demo stylesheet -->
<link type="text/css" rel="stylesheet" href="media/layout.css" />
<link type="text/css" rel="stylesheet" href="themes/calendar_g.css" />
<link type="text/css" rel="stylesheet" href="themes/calendar_green.css" />
<link type="text/css" rel="stylesheet" href="themes/calendar_traditional.css" />
<link type="text/css" rel="stylesheet" href="themes/calendar_transparent.css" />
<link type="text/css" rel="stylesheet" href="themes/calendar_white.css" />
<!-- helper libraries -->
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<!-- daypilot libraries -->
<script src="js/daypilot/daypilot-all.min.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<div class="bg-help">
<div class="inBox">
<h1 id="logo"><a href='http://code.daypilot.org/17910/html5-event-calendar-open-source'>HTML5 Event Calendar</a></h1>
<p id="claim">DayPilot for JavaScript - AJAX Calendar/Scheduling Widgets for JavaScript/HTML5/jQuery</p>
<hr class="hidden" />
</div>
</div>
</div>
<div class="shadow"></div>
<div class="hideSkipLink">
</div>
<div class="main">
<div style="float:left; width: 160px;">
<div id="nav"></div>
</div>
<div style="margin-left: 160px;">
<div id="dp"></div>
</div>
<script type="text/javascript">
var nav = new DayPilot.Navigator("nav");
nav.showMonths = 3;
nav.skipMonths = 3;
nav.selectMode = "week";
nav.onTimeRangeSelected = function(args) {
dp.startDate = args.day;
dp.update();
loadEvents();
};
nav.init();
var dp = new DayPilot.Calendar("dp");
dp.viewType = "Week";
dp.onEventMoved = function (args) {
$.post("backend_move.php",
{
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
},
function() {
console.log("Moved.");
});
};
dp.onEventResized = function (args) {
$.post("backend_resize.php",
{
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
},
function() {
console.log("Resized.");
});
};
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource,
text: name
});
dp.events.add(e);
$.post("backend_create.php",
{
start: args.start.toString(),
end: args.end.toString(),
name: name
},
function() {
console.log("Created.");
});
};
dp.onEventClick = function(args) {
alert("clicked: " + args.e.id());
};
dp.init();
loadEvents();
function loadEvents() {
var start = dp.visibleStart();
var end = dp.visibleEnd();
$.post("backend_events.php",
{
start: start.toString(),
end: end.toString()
},
function(data) {
console.log(data);
dp.events.list = data;
dp.update();
});
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#theme").change(function(e) {
dp.theme = this.value;
dp.update();
});
});
</script>
</div>
<div class="clear">
</div>
</body>
</html>
And backend_events.php :
<?php
require_once '_db.php';
$start = '2015-02-22 00:00:00';
$end = '2015-09-22 00:00:00';
$stmt = $db->prepare('SELECT * FROM events WHERE NOT ((end <= :start) OR (start >= :end))');
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
foreach($result as $row) {
$e = new Event();
$e->id = '1';
$e->text = 'coucou';
$e->start = '2015-05-13T10:00:00';
$e->end = '2015-05-13T12:00:00';
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
It put all events at the same date (It did it like this for tests), but it works !
And when I try to modify backend_events.php, using my database, Events don't appear on the calendar, and I get the error "Cannot read property 'getTime' of undefined" in the console.
I'm not even using what I get from my database as you can see !
<?php
// Insertion de tous les prérequis
include '../Config/prerequis.php';
$bdd = Donnee::getInstance()->connexion;
$start = '2015-02-22 00:00:00';
$end = '2015-09-22 00:00:00';
$stmt = $bdd->prepare('SELECT * FROM CRENEAU WHERE NOT ((Date_fin <= :start) OR (Date_debut >= :end)) AND ID_CONTRAT=16');
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->execute();
$result = $stmt->fetchAll();
class Event {}
$events = array();
// foreach($result as $row) {
// $e = new Event();
// $e->id = $row['ID'];
// $e->text = 'coucou';
// $e->start = implode('T',explode(' ', $row['Date_debut']));
// echo implode('T',explode(' ', $row['Date_debut'])).'<br>';
// $e->end = implode('T',explode(' ', $row['Date_fin']));
// $events[] = $e;
// }
foreach($result as $row) {
$e = new Event();
$e->id = '1';
$e->text = 'coucou';
$e->start = '2015-05-13T10:00:00';
$e->end = '2015-05-13T12:00:00';
$events[] = $e;
}
header('Content-Type: application/json');
echo json_encode($events);
?>
I've tried to fix it for days, I even ask friends who are more qualified, I can find the solution. So if you have idea I would be gratefull !
Thanks,
Marine.
We've found the solution.
So it was an encodind problem,
I do an include '../Config/prerequis.php';
An in the file prerequis.php I do other include, an files I was trying to include where encode in UTF-8 instead of UTF-8 without Bom.
I works perfectly now!

Multyple YQL-json data request/return

I'm back here with this problem:
I've got an API page where I get son data files in response of requests.
So I've created a js file that gets cross domain json through yql and returns json data decoded into a string I pass to php to be inserted into a MySql database and returned into a table.
So I know I can interrogate API with an url like this ..../usd-gold.json where I get informations about exchange between US dollar and Gold, but if I want to get the opposite change I should interrogate ..../gold-usd.json.
This is the question finally.
How can I get multiple json interrogation in order to get back json data, decode it, combine togheter the data and send it to php.
In other words: how can I make an multiple interrogation like idr-gold.json, gold-dir.json, usd-gold.json, gold-use.json and so on for all the currency, combine code, transmit it to php and work on mysql.
Here is the code I use, for one query.
JS code/file:
// JavaScript Document
$(document).ready(function(){
var container = $('#target');
$('.ajaxtrigger').click(function(){
doAjax($(this).attr('href'));
return false;
});
function doAjax(url){
// if it is an external URI
if(url.match('^http')){
// call YQL
// TEST
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=json'&callback=?", // QUESTO è URL cui segue la "," e poi function(data)
// this function gets the data from the successful
// JSON-P call
function(data){
// if there is data, filter it and render it out
if(data.results[0]){
var data = filterData(data.results[0]);
container.html(data);
// alert(data); // MIO TEST
document.getElementById("prova1").value = data; //MIO
// TEST
var obj = $.parseJSON(data);
document.getElementById("provabis").innerHTML = obj.buy.currency+"/"+obj.sell.currency+" "+obj.offer[0].rate+" "+obj.offer[0].amount+" "+obj.offer[0].seller.name;
// alert(obj.sell.currency);
// TEST END
// otherwise tell the world that something went wrong
} else {
var errormsg = "<p>Error: can't load the page.</p>";
container.html(errormsg);
}
}
);
// if it is not an external URI, use Ajax load()
} else {
$('#target').load(url);
}
}
// filter out some nasties
function filterData(data){
data = data.replace(/<body>/,'');
data = data.replace(/<?\/body[^>]*>/g,'');
data = data.replace(/[\r|\n]+/g,'');
data = data.replace(/<--[\S\s]*?-->/g,'');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
data = data.replace(/<script.*\/>/,'');
return data;
}
});
here is html code/file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> </meta>
<title>
Under Developement
</title>
<link type="text/css" href="styles.css" rel="stylesheet"></link>
</head>
<body>
<div id="doc" class="yui-t7">
<div id="hd" role="banner">
<h1>
Ajax with jQuery - using YQL
</h1>
</div>
<div id="bd" role="main">
<h2>
Demo
</h2>
<ul>
<li>
<a class="ajaxtrigger" href="ajaxcontent.html">
Load Ajax Content
</a>
</li>
<li>
<a class="ajaxtrigger" href="http://www.API LINK.json">
<!-- <a class="ajaxtrigger" href="http://www.API LINK.json
</a><br>
<a class="ajaxtrigger" href="http://www.API LINK.json">
<!-- <a class="ajaxtrigger" href="http://www.API LINK.json"> -->
Get cspro2.json
</a>
</li>
</ul>
<div id="target">
</div>
<h2>
Formatted List
</h2>
</div>
<div id="prova2">
</div>
<h2>
TEST
</h2>
</div>
<form action="jsontodb10.php" method="post">
Json code: <br>
<textarea id="prova1" style="width:40%;height:40em;" name="jsonCode"> </textarea>
<!-- metti qui il pulsante per submittare al php -->
<br>
<input type="submit">
</form>
<textarea id="provabis" style="width:40%;height:40em;"></textarea>
<script src="http://code.jquery.com/jquery-latest.pack.js"> </script>
<script src="code.js"></script>
<script src="using-yql7.js"></script>
</div>
</body>
</html>
and finally php code/file:
<!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" />
<link href="table-db.css" rel="stylesheet" type="text/css">
<title>Database show</title>
</head>
<body>
<?php
//inserisci il reset della variabile che non manda in loop il force update
$submitVerify = $_POST["_Submit"];
if($submitVerify=="force Update"){
// unset($submitVerify);
echo ("<script type='text/javascript'>location.reload();</script>");
};
//connect to mysql db
$servername = "localhost";
$username = "my user";
$password = "";
$dbname = "my db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";
// QUI METTIAMO la verifica circa il RecordTime ed il TimeNow (così che non si registrino più di 1 Record/ 2 hour)
$timeNow = date('Y-m-d H:i:s'); // ora adesso
$time = strtotime($timeNow); // settato l'ora adesso
$timeRange = date('Y-m-d H:i:s',strtotime('-2 hours', $time)); // l'ora adesso -2 ore
$sqlsearchTime = "SELECT DateTimeSave FROM Valuta ORDER BY ID DESC LIMIT 1";
$searchresultTime = mysqli_query($conn, $sqlsearchTime);
if (mysqli_num_rows($searchresultTime) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($searchresultTime)) {
echo "\n Last record in database was at: " . $row["DateTimeSave"]. "<br>";
if ($row["DateTimeSave"] > $timeRange) // se l'orario estratto dal database è < dell'orario attuale -2 ore
{
echo('hey sono passate meno di due ore, non inserirò un altro dato a meno che tu non mi forzi <br />'); // allora apri il database ed inserisci l'ultimo dato ottenuto e mostra il contenuto del database
// goto showData;
goto insertData;
}
else // se l'orario è maggiore
{
echo('si che possiamo mettere questo nuovo dato nel database <br />'); // allora mostra solo il contenuto e rimanda a al tasto che forza l'estrazione del dato e l'inserimento dei dati ne db e mostra contenuto
goto insertData;
};
}
} else {
echo "0 results";
};
// NOME funzione
insertData:
//VALUES from JSON
//read the json file contents
//$jsondata = file_get_contents('idr-gold.json');
//$jsondata = file_get_contents('idr-gold.txt');
//convert json object to php associative array
//$data = json_decode($jsondata, true);
//get the value details
$content = $_POST["jsonCode"];
//$jsondata = file_get_contents('idr-gold.txt');
//$json = json_decode($content, true);
//convert json object to php associative array
$data = json_decode($content, true);
$buycurrency = $data['buy']['currency'];
$sellcurrency = $data['sell']['currency'];
$sellrate = $data['offer'][0]['rate'];
$sellamount = $data['offer'][0]['amount'];
$sellername = $data['offer'][0]['seller']['name'];
$offer = $data['offer'];
//se l'offerta nulla metti "no record"
if($offer === NULL)
{
$sellrate = 'No Record';
$sellamount = 'No Record';
$sellername = 'No Record';
};
//VALUES RECORDSNORECORDS (OK) questo setta se c'è o meno un Record
if($sellername != NULL)
{
$recordsNoRecords = TRUE;
} else {
$recordsNoRecords = FALSE;
};
//VALUES DATE&HOUR (OK) qui setta l'ora dell'inserimento e poi inserisce i dati
date_default_timezone_set('UTC+1');
$timestamp = date('Y-m-d H:i:s');
$sqlinsert = "INSERT INTO Valuta (BuyCurrency,SellCurrency,SellRate,SellAmount,SellerName,LinktoPage,Records NoRecords,DateTimeSave)
VALUES ('$buycurrency','$sellcurrency','$sellrate','$sellamount','$sellername','test','$recordsNoRecords','$timestamp')";
if ($conn->query($sqlinsert) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sqlinsert . "<br>" . $conn->error;
} goto showData;
// NOME funzione
showData:
// QUERY X VEDERE
$sqlsearch = "SELECT BuyCurrency, SellCurrency, SellRate, SellAmount, SellerName, LinktoPage, DateTimeSave FROM Valuta";
$searchresult = mysqli_query($conn, $sqlsearch);
if (mysqli_num_rows($searchresult) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($searchresult)) {
echo "\n Currency to buy: " . $row["BuyCurrency"]. " - Currency to sell: " . $row["SellCurrency"]. " - Sell Rate " . $row["SellRate"]. " - Amount on sale: " . $row["SellAmount"]. " - Seller Name: " . $row["SellerName"]. " - Lik to page: " . $row["LinktoPage"]. " - Date & Time of record: " . $row["DateTimeSave"]. "<br>";
}
} else {
echo "0 results";
};
$conn->close();
?>
<!-- bottone per forzare l'aggiornamento -->
<form name="update" action="" method="post">
se vuoi forza
<input type="submit" name="_Submit" value="force Update">
</form>
<?php
$submit = $_POST["_Submit"];
if($submit=="force Update"){
echo ("facciamolo!");
// goto insertData;
}else{
echo ("SUCA!!");
// goto showData;
};
?>
<br />
<br />
<br />
<br />
<?php
// TABELLA
//connect to mysql db
$servername = "localhost";
$username = "";
$password = "";
$dbname = "my db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";
$sql = "SELECT BuyCurrency,SellCurrency,SellRate,SellAmount,SellerName,LinktoPage,DateTime Save FROM Valuta ORDER BY ID DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
echo '<tr><th>Buy</th><th>Sell</th><th>Rate</th><th>Amount</th> <th>Seller</th><th>Link</th><th>Time Record</th></tr>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["BuyCurrency"]."</td> <td>".$row["SellCurrency"]."</td><td>".$row["SellRate"]."</td> <td>".$row["SellAmount"]."</td><td>".$row["SellerName"]."</td> <td>".$row["LinktoPage"]."</td><td>".$row["DateTimeSave"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
};
$conn->close();
?>
</body>
</html>
Thx in advance for help!
UPDATE porpose of the script
The porpose of the script is to have a site where i can show the retrieved data from an api that returns json or xml.
So I have tryed the way that seemed to me the easyest to retrieve json data (xml was harder if i understood well). I found that YQL was easy to get cross-domain data with json files.
What I read than, is that json answer, when you try to access to different files at the same time, might have transfert rate limitations and I checked that json data in real time get about 1/2 sec to give answer.
So this is what I thought.
I create a js form that create the url to the api answer, I recive data throw YQL, that code to php and insert it into db. So the user gets mysql tables with saved data in spite of having to wait for site to get all the data in real time.
The optimal goal for me would be:
1) have a db that every 4 hours get the json from api;
2) update data saved;
3) when user Open page could interrogate db or force json data retrieve in real time (updateing db).
That's the final porpose.
Thx for your time.

Categories