JSON array values not being read by JQuery - javascript

I’m reading X,Y Coordinates from MySQL Database.
2 files(I can post the connection file if needed): coordinate_array, and map.php
coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the JS/Jqueryt part.
updated PHP code and JQuery CODE.. still does not work!?
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$coordinate_sql = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$coordinate_sql);
//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('x' => $row['x_coord'],
'y' => $row['y_coord']);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this as the result for the array:
[{"x":"20","y":"20"},{"x":"30","y":"30"},{"x":"40","y":"40"},{"x":"50","y":"50"}]
map.php : This is the part where is not entirely working. I'm trying to get the values from json_encode with JQuery but I get no output on screen.
Don't know which of these two I should use
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
Need help here please
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
//I have no idea how to get the encoded values
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
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>

The JSON formal definition tends to have an object (or, key-associative-array: {}) as the root of any JSON object, as opposed to an array ([]).
To wrap it inside one associative object:
$deskOutput = array("coords" => $desk);
echo json_encode($deskOutput); //encode array
Then, on the JavaScript side, you will just need to get "each(data.coords," and you'll have your array.
For that matter, it seems like you're putting unnecessary complexity in your array structure at the PHP level. How about this?
$desk[] = array("x" => $row['x_coord'], "y" => $row['y_coord']));
That will create just one object for each x/y set. I'll leave it to you to figure out how you could simplify your JavaScript accordingly.

First just make $desk like this:
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array('x' => $row['x_coord'], 'y' => $row['y_coord']);
}
echo json_encode($desk);
And call the php script like so:
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
I'm going to test this really quick to make sure I got everything right.
Edit: Okay, I tested this, it works.

Related

Save data to JSON File in correct format - PHP

I am currently saving click co-ordinates to a JSON file through the use of the following code:
onmouseup = function(e){
var Clicks = {};
Clicks.state = {
cX: e.clientX,
cY: e.clientY,
}
$.ajax({
type : "GET",
url : "PHP/save_json.php",
data : {
state : JSON.stringify(Clicks.state)
}
});
}
<?php
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
fwrite($fh, $stringData);
fclose($fh)
?>
However with the above code I am saving the coordinates in the following incorrect format:
{"cX":467,"cY":374}{"cX":56,"cY":474}
Can anyone please help me to save the coordinates in a JSON array rather than in seperate JSON entries?
I would like the file to be as follows, were the coordinates are added onto the already existing JSON array within the file:
{
"ID":["1","2"],
"cX":["467","56"],
"cY":["374","474"]
}
What you need to do is:
Open the clicks.json file and read the entire contents.
Turn this into an instance of stdClass by using json_decode. This will give you a PHP object that you can modify using normal PHP functions and syntax.
Use json_decode on the JSON that you receive from your client.
Use array_push to push the new values from the client into the arrays stored in the file (something like array_push($fileJson->cX, $clientJson->cX);)
Use json_encode to encode $fileJson again.
Write it back to the file.
This assumes that the clicks.json file is already correctly formatted JSON with the arrays already created etc.
Given the current arrangement of the key and value bits, it's apparent that some sort of transformation is needed in the JSON data before it is written to the file. Where this transformation is done is definitely a matter of an opinion. However, assuming that you receive following JSON data in PHP:
[{"cX":467,"cY":374},{"cX":56,"cY":474}]
The PHP code can be written as (illustrated with static input):
$myFile = "JSON/clicks.json";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $_GET["state"];
$json_array_source = json_decode($string, true);
$json_array_target = array();
foreach($json_array_source as $key=>$value){
$json_array_target["ID"][] = $key + 1;
foreach($value as $sub_key => $sub_value){
$json_array_target[$sub_key][] = $sub_value;
}
}
$transformed_string = json_encode($json_array_target);
fwrite($fh, $transformed_string);
fclose($fh);
If you were to echo $transformed_string;, you'd see:
{"ID":[1,2],"cX":[467,56],"cY":[374,474]}
Which is what will be written to the file.
You need load data to array, add new data and save back to file.
I think you don't need save numbers in strings.
These code create new file if not exists.
<?php
// test input data
if(isset($_GET['state']['cX']) &&
isset($_GET['state']['cY']) &&
is_numeric($_GET['state']['cX']) &&
is_numeric($_GET['state']['cY']) )
{
// ok
} else {
exit('Bad data format');
}
$myFile = __DIR__ . "/JSON/clicks.json";
// step 1, load data from file to array
$array = file_exists($myFile) ?
json_decode(file_get_contents($myFile), true) :
[];
// step 2, add data to array
$array['ID'][] = isset($array['ID']) ? (count($array['ID']) + 1) : 1;
$array['cX'][] = (int) $state['cX'];
$array['cY'][] = (int) $state['cY'];
// step 3, save array back to file
file_put_contents($myFile, json_encode($array));
Or you can use other file format where will be possible to append file. The easiest format for static structured data could be CSV
Use json_encode to convert your string to an object, then convert it back to a string using json_decode and the JSON_PRETTY_PRINT option.
$stringData = json_decode(json_encode($_GET["state"]), JSON_PRETTY_PRINT);
http://php.net/manual/en/function.json-encode.php

How can I use decoded JSON data inside PHP?

Using this plugin I need to draw an audio waveform with pre-rendered data.
I stored JSON data inside MySQL as {"sample_rate":44100,"samples_per_pixel":4410,"bits":8,"length":2668,"data":[0.13,0.19,0.15,0.11,0.13,0.13,0.24,0.35 ...]}
So I tried:
PHP
$json = $row['wave'];
$json_array = json_decode($json);
$json_wave = implode(',', $json_array->data);
HTML
<div data-track-wave="'.$json_wave.'" id="play'.$row['id'].'" class="track"></div>
JS
function createWaveform(json) {
$( "#waveformbottom" ).empty();
var linGrad = document.createElement('canvas').getContext('2d').createLinearGradient(0,0,0,170);
linGrad.addColorStop(0, '#ff3b25');
linGrad.addColorStop(0.5, '#ff0018');
var wavesurferbottom = WaveSurfer.create({
container: document.querySelector('#waveformbottom'),
waveColor: '#b3b3b3',
progressColor: linGrad,
backend: 'MediaElement',
mediaType:'audio',
height:'48',
cursorColor:'#fff',
cursorWidth:'0',
normalize:true,
barWidth:'2'
});
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = [json];
//Draw peaks
wavesurferbottom.drawBuffer();
$(window).resize(function(){
if($(this).width() != width){
widthbottom = $(this).width();
wavesurferbottom.drawer.containerWidth = wavesurferbottom.drawer.container.clientWidth;
wavesurferbottom.drawBuffer();
}
});
}
$(document).on('click touchend', '.track', function(e) {
var wave_data = $(this).data('track-wave');
createWaveform(json);
e.preventDefault();
});
A debug of my wave_data shows that is correct like 0.01,0.13,0.19,0.15,0.11,... however the waveform is not drawn.
Instead if I set wavesurferbottom.backend.peaks = [0.01,0.13,0.19,0.15,0.11,...];it works.
I'm not a JSON expert, what am I doing wrong?
The difference is that one is a string (which isn't valid JSON anyway - it's just a list of comma separated numbers):
data-track-json="0.01,0.13,0.19,0.15,0.11"
var json = $(this).data('track-json'); // a string
And the other is a JS array:
var x=[0.01,0.13,0.19,0.15,0.11];
A simple approach is to split it by , - that'll convert your string into the JS array that you need, like so:
var samples = $(this).data('track-json').split(','); // Renamed because it's not JSON
..
createWaveform(samples);
It's also worth noting that you'll get an array of strings rather than an array of numbers, but many JS libraries handle that. If you wanted to go the JSON route, then make sure your attribute contains square brackets:
data-track-json="[0.01,0.13,0.19,0.15,0.11]"
The PHP to create that could look like this:
$json_wave = '['.implode(',', $json_array->data).']';
Then use a JSON.parse call to convert it into a suitable array of number types:
var samples = JSON.parse( $(this).data('track-json') );
If you still want to use JSON
PHP
$json = $row['wave'];
$object = json_decode($json);
$json_wave = json_encode($object->data);
This is a JSON string, presumably something like [1,2,3,4]
HTML unchanged
<div data-track-name="'.$row['name'].'" data-track-id="'.$row['id'].'" data-track-json="'.$json_wave.'" id="play'.$row['id'].'" class="track song-play-btn playthistrack"></div>
JS parse the JSON where you've identified the problem
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = JSON.parse(json);
wavesurferbottom.backend.peaks will be an array of Numbers - presumably what the rest of the code expects

generating multidimensional object with array

I am generating an object like this:
As you can see education is an array inside an object,
but what I want is for degree_1 and major_1 and their values to be in the same object.
This is how I want it but with education as an array:
One other thing:
When I var_dump it in my php it is just fine with the arrays and everything. But my javascript gets the second image above- object of object when it was just an array..
public function show($id)
{
$tmp = array();
$post = array();
$postInfo = Post::find($id);
$params = DB::select( DB::raw("SELECT param.*, sys_param_values.*,param_value.*,type_post.*,
param.name AS paramName,
doc_param.name AS docParamName
FROM param
LEFT JOIN doc_param ON param.doc_param_id = doc_param.id
LEFT JOIN sys_param_values ON param.id = sys_param_values.param_id
LEFT JOIN param_value ON sys_param_values.value_ref = param_value.id
LEFT JOIN type_post ON sys_param_values.ref_id = type_post.id WHERE type_post.id = ".$id));
$isMultiple = false;
$post['postInfo'] = $postInfo['original'];
foreach($params as $k=>$v) {
$iteration = $v->iteration;
$docParamName = $v->docParamName;
$paramName = $v->paramName;
if($v->value_ref == null) {
$value = $v->value_short;
} else {
$value = $v->value;
}
if($iteration) {
$post[$docParamName][$iteration][$paramName] = $value;
// need to return education as array not as object
// $post[$docParamName][] = array($paramName=>$value) ;
}elseif(!$iteration) {
$post[$docParamName][$paramName] = $value;
}
}
return Response::json($post);
}
Make first element from education to 0, now it is 1, so that's why json_encode is parsing it as an object.
I don't know what you data source looks like, but it looks to me that you're fetching vertical data and them want to display it horizontally. If that is the case your data need to be stored in a way that simply looping is enough, if not some PHP logic will be required.
We can't really help you on that until you show us an example of your table contents.
Cheers

Manipulating JSON data to create javascript array of lat/lngs in Google Maps API V3

I'm trying to use lat/lng values retrieved from MySQL to create an array of waypoints for use in the GMaps API. I have the code below but with my limited javascript knowledge am struggling to push this retrieved data into a javascript array to define as the waypoints data.
I've looked at a few online examples and so far I have managed to get a parsing script to retrieve the data with no problems and call this within the page I have the maps instantiated on:
makeRequest('parsedata.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
The parsedata.php code:
<?php
include 'session.php';
$query = "SELECT itinerary_link.itineraryID, itinerary_link.coursesID, itinerary_courses.coursename,
courses.lat, courses.lng FROM itinerary_link LEFT JOIN
itinerary_courses ON itinerary_link.coursesID = itinerary_courses.coursesID LEFT JOIN
courses ON courses.coursename = itinerary_courses.coursename WHERE itineraryID=6 ORDER BY coursename";
$result = mysqli_query($dbc, $query);
$rows = array();
while ($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode( $rows );
?>
And sample output from this:
[{"itineraryID":"6","coursesID":"20","coursename":"Carnoustie Championship Course","lat":"56.497414","lng":"-2.720531"},{"itineraryID":"6","coursesID":"21","coursename":"Troon Old Course","lat":"55.534203","lng":"-4.642833"}]
Basically I can't work out how to manipulate this output to create the required javascript array of lat/lngs to feed in as the waypoints for a directions service instance I have running on the page.
As always, any pointers much appreciated. Cheers.
//create an array for the waypoints
var waypoints=[];
//only up to 8 waypoints are allowed without business-license
for(var i=0;i<8 && i<data.length;++i) {
//push a LatLng-object to the array
waypoints.push(new google.maps.LatLng(data[i].lat,data[i].lng));
}
//use the waypoints
//doSomethingWith(waypoints);

send data from php to javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a question regarding data transmission from php to javascript. I gather some data from database and I format them like this:
for($i=0;$i<(sizeof($lt_periods_query['period_id']));$i++){
$period_id = $lt_periods_query['period_id'][$i];
$lt_id = $lt_periods_query['lt_id'][$i];
$period_name = $lt_periods_query['period_name'][$i];
$fDate = $lt_periods_query['fromDate'][$i];
$tDate = $lt_periods_query['toDate'][$i];
$minStay = $lt_periods_query['min_stay'][$i];
$nightly_rate= $lt_periods_query['nightly_rate'][$i];
if (strStartsWith($fDate, $currentYear)=='true'){
$year = $currentYear;
} else if(strStartsWith($fDate, $nextYear)=='true'){
$year = $nextYear;
}
$temp_period_details = array();
$temp_period_details['period_id'] = $period_id;
$temp_period_details['lt_id'] = $lt_id;
$temp_period_details['period_name'] = $period_name;
$temp_period_details['fromDate'] = $fDate;
$temp_period_details['toDate'] = $tDate;
$temp_period_details['min_stay'] = $minStay;
$temp_period_details['nightly_rate'] = $nightly_rate;
$periods[$year][$period_name] = $temp_period_details;
}
And I am able to see them when I print as like this:
echo "RULE for 6 days <br>";
$days= '5';
$selPeriod = 'off_peak';
$selYear = '2011';
echo $periods[$selYear][$selPeriod]['period_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['lt_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['period_name'];
I know that php is working on the server side and javascript is working on the client side.
I want to get the data from javascript side by sending some parameters like this (I know why this is not working but I do not know how I can achieve such data transfers):
<script type="text/javascript">
$(function(){
getData();
function getData(){
var days= '5';
var selPeriod = 'off_peak';
var selYear = '2011';
//var xxx = '<?php echo $periods[\''+selYear+'\'][\''+selPeriod+'\'][\'fromDate\'] ;?>';
//var xxx = '<?php include($periods['2011']['off_peak'][''])?>;
}
});
Can anyone advice me a way to gather data from php to javascript by sending some parameters.
To communicate data structures from PHP to Javascript, inject a JSON value like this:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
This can be used to properly escape scalars, arrays, objects, etc.
There's the AJAX method, and there's the echoing method. The former is more flexible, while the latter is a lot simpler and doesn't require you to cope with AJAX errors.
For the former, there are plenty of examples around the place on how to use AJAX. The latter can be achieved quite simply:
<script type="text/javascript">
var phpVar = <?php echo ($phpVar); ?>;
</script>
Which approach is approporite depends on what data your javascript needs and what it needs it for. If you're needing to do a lot of server interaction, then working with AJAX is the avenue you should be investigating. However, if all you need is an initial value to initialize a javascript, then the latter approach is a lot easier to implement.
Simple AJAX approach.
Put all your data into single array. Then use json_encode to encode your data to JSON format.
$data_array = array();
//assigning your data to single array here
$data_array['param1'] = 'value1';
echo json_encode($data_array);
Then in your JavaScript code use AJAX to call you script. For example use great jQuery library for this (http://api.jquery.com/jQuery.getJSON/).
<script type="text/javascript">
$.getJSON('http://www.example.com/my_script.php', function(data) {
alert(data.param1); //this should alert 'value1'
});

Categories

Resources