I updated my code. It has Javascript,PHP,JSON and JQuery. I’m reading X,Y Coordinates from
MySQL Database.
I am now using 3 files : coordinate_array, db_conn and map.php
Connection :
<?php
//declaring connection
$db_user = "u";
$db_pwd = "p";
$db_server = "v";
$db_name = "sandbox";
//1. connection to the database
$conn = mysqli_connect($db_server, $db_user, $db_pwd);
//check connection
if(!$conn){
die("Database connection failed: " . mysqli_error());
}else{
echo "connected to MySQL<br>";
}
// 2. Select a database to use
$db_select = mysqli_select_db($conn, $db_name);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
mysqli_close($conn);
?>
In coordinate_array: I am making a multidimensional arrays so I can draw all of the rectangles being
fetch by my query, I then use json_encode($desk). I am ignoring the coordinate_id from the table
since I only need x,y values for the Javascript part.
<?php
$select_coordinate_query = "SELECT * FROM coordinates";// WHERE coordinate_id ='1'
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk = array( array("x" => $row['x_coord']),
array("y" =>
$row['y_coord'])
);
// Frame JSON
// Return the x, y JSON here
echo json_encode($desk);
} //end while loop
?>
In map.php : I am trying to get those value with the use of JQuery. I want to get the values and run a
loop that will execute my Paint function which will keep drawing rectangles for every row thats in the
table. I am very new with JSON and JQuery and starting to use it.
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600"
height="500"></canvas>
<script type="text/javascript">
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('coordinate_array.php', function(data) {
/* data will hold the php array as a javascript object */
if(data != null){
$.parseJSON(data);
$(data).each(Paint(x,y)){
//get values from json
//for every row run the functionpaint by passing X,Y coordinate
});//end getJson
}//end if
}); //end rdy func
});//end func
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
</div> <!-- end div section_a -->
Also, do I have the correct syntax for my when including my jquery file.. its in the same as
every other file that I’m using.
Another question I have is: Is it good to include the connection file in every file and close it at the end
or keep the connection open in my file where I havethe connection established?
Thank you in advance it’s much appreciated!
I would like to suggest a better way to keep the code simple and clean.
Create a web service interface to return the x,y data in an array.
This interface can read from the database and shall return x,y co-ordinates in JSON.
Use Jquery Ajax call to get these details and paint the screen.
Better use RxJS for easier painting.
Here is the sample code for web interface:
<?php
// I assume you have not created connection object -- I don't see one in your code
$conn=mysqli_connect("localhost","my_user","my_password","my_db"); // replace the credentials and db name
// Check connection
$select_coordinate_query = "SELECT * FROM coordinates";
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good -- ## Better check for row count
if($result === false)
{
die(mysqli_error());
}
//array that will have number of desks in map area
while($row == mysqli_fetch_assoc($result)){ // double equal to missing...you will never receive the data
//get desk array count
//THIS IS WHERE I NEED HELP**
$desk = array( array("x" => $row['x_coord']),array("y" => $row['y_coord']) );
//x, y coordinates
$x_pos = $desk['x'];
$y_pos = $desk['y'];
//x,y width and height
$x_size = $x_pos + 40;
$y_size = $y_pos + 10;
// Frame JSON
// Return the x, y JSON here
} //end while loop ?>
Here is the client code:
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
function callWS()
{
// Make XHR call here and read JSON values
// Loop through and paint by calling f(Paint)
}
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
ctx.strokeRect(x, y,100 , 100);
}
</script>
</div>
You can call these functions in any event you would want. Code is untested. Note that you were creating Canvas many times earlier but here it's created once and you can draw squares on the canvas.
Related
I have some problems trying to redraw some markers (on google maps) from a database, use the form jquery
Index.html:
var map;
var datos;
function updateLocations(){
var post= $.post('php/getLoc.php',{table: "Auto"), function f(data){
datos =[]; //clear array with the last positions
datos = data;
drawAutos(datos); }); }
php/getLoc.php:
$link = mysql_connect("localhost","root","") or die('could not connect: '.mysql_error());
mysql_select_db("database") or die ('could not select db');
$autos= "SELECT * FROM autos ORDER BY auto_id ASC";
$result=mysql_query($autos) or die('query fail'.mysql_error());
$datos= array();
while($row= mysql_fetch_assoc($result)){
$datos[] = array(
0=>$row['taxi_id'],
1=>$row['lat'],
2=>$row['lng'],
3=>$row['availability']);}
$out = array_values($datos);
var_dump(json_encode($out));
mysql_free_result($result);
mysql_close($link);
The query is correct, but I get the information otherwise. there is a way to remove the string () "" (see picture), I have tried using $.parseJSON(data) and $.getJSON(data) but not work for me =(
echo json_encode($out); instead of var_dump($out);. Also, mysql is depreciated. Use mysqli or PDO or something else. The Object Oriented Approach will save you time. Also, you can $mysqli_result->fetch_all(MYSQLI_ASSOC) instead of making your while loop.
Ok, is working now :), thanks to PHPglue, I use
PHP File:
echo json_encode($out)
I also do in Index File:
var obj = $.parseJSON(data);
drawAutos(obj);
we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};
I have the following HTML fragment, using PHP and JavaScript:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
var imageIndex = 0; // index into imageNames array
var imageHeight = 400; // height of image; changed by user clicking size buttons
var imageNames; // names of images user can view in this album
function pageLoaded() // execute this when the page loads.
{
// PHP -- generate the array of image file names
<?php
function getImageNames($directory)
{
$handle = opendir($directory); // looking in the given directory
$file = readdir($handle); // get a handle on dir,
while ($file !== false) // then get names of files in dir
{
$files[] = $file;
$file = readdir($handle);
}
if ($files[0] === ".") { unset($files[0]); } // Unix specific?
if ($files[1] === "..") { unset($files[1]); }
foreach($files as $index => $file) // only keep files with image extensions
{ $pieces = explode(".", $file);
$extension = strtolower(end($pieces));
if ($extension !== "jpg") { unset($files[$index]); }
}
$files = array_values($files); // reset array
natcasesort($files); // and sort it.
return $files;
}
?>
<?php $imageDirectory = $_GET['directory'] . '/';
$imageNames = getImageNames($imageDirectory);
?>
imageNames = <?php echo json_encode($imageNames); ?>;
imageHeight = 400;
imageIndex = 0;
reloadImage(); // loads the first image based on height and index
}
There is more after this, but this part doesn't refer to anything there, and my problem already exists by this point in the HTML output.
The problem is that, 5 lines from the end, I do a json_encode of an array of filenames. The output I get from this looks thusly:
imageNames = [{"59":"01-hornAndMusic.JPG","58":"02-DSC_0009.JPG","57":"03-DSC_0010.JPG","56":"04-Discussion.JPG","55":"05-DSC_0015.JPG","54":"06-DSC_0016.JPG","53":"07-DSC_0019.JPG","52":"08-strings.JPG","51":"09-strings2.JPG","50":"10-rehearsing.JPG","49":"11-StringsBigger2-001.JPG","48":"12-DSC_0041.JPG","47":"13-DSC_0046.JPG","46":"14-ensemble.JPG","45":"15-ensemble2.JPG","44":"16-DSC_0052.JPG","43":"17-rehearsing3.JPG","42":"18-rehearsing4.JPG","41":"19-rehearsing-001.JPG","40":"20-stringsBigger2.JPG","39":"21-rehearsing-002.JPG","38":"22-rehearsing-003.JPG","37":"23-ensemble3.JPG","36":"24-winds.JPG","35":"25-rehearsing-004.JPG","34":"26-stringsEvenBigger.JPG","33":"27-concentration.JPG","32":"28-concertMistress2.JPG","31":"29-stringsMore.JPG","30":"30-stringsMore-001.JPG","29":"31-stringsMore-002.JPG","28":"32-stringsMore-003.JPG","27":"33-stringsMore-004.JPG","26":"34-stringsMore-005.JPG","25":"35-DSC_0076.JPG","24":"36-stringsMore-007.JPG","23":"37-stringsMore-008.JPG","22":"38-stringsMore-009.JPG","21":"39-oboes.JPG","20":"40-winds-001.JPG","19":"41-DSC_0085.JPG","18":"42-DSC_0086.JPG","17":"43-percussion.JPG","16":"44-DSC_0088.JPG","15":"45-violinAtRest.JPG","14":"46-laughterInTheWoodwinds.JPG","13":"47-conducting-001.JPG","12":"48-DSC_0095.JPG","11":"49-DSC_0096.JPG","10":"50-AllTogetherNow.JPG","9":"51-DSC_0106.JPG","8":"52-horns.JPG","7":"53-DSC_0111.JPG","6":"54-conducting.JPG","5":"55-conducting-002.JPG","4":"56-conducting-003.JPG","3":"57-conducting-005.JPG","2":"58-DSC_0120.JPG","1":"59-DSC_0122.JPG","0":"60-everybody.JPG"}];
so I have the keys as well as the values of this hybrid PHP map/array thingie. What I want is just the values, put into a string array in the JavaScript.
I've gotten this to work sometimes, but not others, and I don't know the difference.
I think applying array_values function on $imageNames before encoding them should do the trick.
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;
I'd do this:
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;
I’m reading X,Y Coordinates from MySQL Database.
2 files, pretend the connection is there : coordinate_array, and map.php
Update here In coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the Javascript part.
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$select_coordinate_query = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
$desk = array(); // just added
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array( array("x" => $row['x_coord']),
array("y" => $row['y_coord'])
);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this :
[[{"x":"20"},{"y":"20"}],[{"x":"30"},{"y":"30"}],[{"x":"40"},{"y":"40"}],[{"x":"50"},{"y":"50"}]]
In map.php : I am trying to get those value with the use of JQuery. I want to get the values and run a loop that will execute my Paint function which will keep drawing rectangles for every row thats in the table. I am very new with JSON and JQuery and starting to use it.
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
NEED HELP HERE PLEASE
//I have no idea how to get the encoded values
$(document).ready(function(){
$.getJSON('coordinate_array.php', function(data)){
$.each(data, function(k,v){
Paint(v[0].x, v[1].y);
});//end each
});//end get json
});//end rdy func
I WANT TO EXECUTE THIS FUNCTION
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
Thank you in advance it’s much appreciated!
You're doing the json wrong. it should be encoded AFTER your DB fetch loop completes. Since you're doing the encoding inside the loop, you're spitting out multiple independent JSON-encoded strings, which will be treated as a syntax error on the receiving end.
e.g.
while($something) {
echo json_encode($some_array);
}
will spit out
[something][something][something]
three separate json-encoded arrays jammed up against each other. What you want is something more like this:
while($something) {
build_array();
}
echo json_encode($array);
which would spit out
[something,something,soemthing]
instead.
Try to use
header('Content-Type: application/json');
in coordinate_array.php
Alright, so me and my buddy is creating a game and a website, he is working on the game, and i am working on the site. The game is built using the ImpactJS engine, and everything works fine and so, but the problem we have ecountered is how we should save the highscore.
Currently we got a website built, where you can log in and then play, and our idea is that after you finish the level (or when you die) you get a score, then that score gets send to the database along with the current user thats logged in. We got the function that would do that, but the problem is that we dont know how we should send the score from the javascript file, to the actuall database.
So this is how things are looking right now:
First we actually got the highscore function in the main.js
Main.js
draw: function() {
this.parent();
this.background.draw(0,0);
var x = ig.system.width/2;
var y = ig.system.height/2 - 20;
this.gameOver.draw(x - (this.gameOver.width * .5), y - 30);
var score = (this.stats.kills * 100) - (this.stats.deaths * 50);
this.instructText.draw('Total Kills: '+this.stats.kills, x, y+30,
ig.Font.ALIGN.CENTER);
this.instructText.draw('Total Deaths: '+this.stats.deaths, x, y+40,
ig.Font.ALIGN.CENTER);
this.instructText.draw('Score: '+score, x, y+50, ig.Font.ALIGN.CENTER);
this.instructText.draw('Press Spacebar To Continue.', x, ig.system.height -
10, ig.Font.ALIGN.CENTER);
}
We understand that its the +score that we have to insert into the database.
Then we got the DB class, thats going to insert the data into the database (and by the way, im working object oriented since this is a school project and we have to do it this way)
DB.php
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field) {
$values .= '?';
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
And then lastly we got the highscore class:
Highscore.php
public function create($fields = array()) {
if(!$this->_db->insert('highscores', $fields)) {
throw new Exception('There was a problem saving your score. Sorry!');
}
}
Yeah, so basicaly we dont know how we should get the +score from the external javascript file, and send it into to php...
We did do some research and found out that maybe we should use Ajax for this? Anyhow, anybody can lend a hand?