Reputation: 149
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!
Upvotes: 0
Views: 166
Reputation: 147
Try to use header('Content-Type: application/json'); in coordinate_array.php
Upvotes: 0
Reputation: 360782
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.
Upvotes: 1