I want to send three arrays of data namely vertexa, vertexb and edge_id to HTML page including JavaScript so as to run an algorithm Dijkstra on the vertices. Should I use JSON commands for this?
-
take a look at the php function json_encode - you can pass multidimensional associative arrays to it.Zevan– Zevan2010-11-27 06:31:00 +00:00Commented Nov 27, 2010 at 6:31
2 Answers
You'll want to use json_encode on the data, like
<?php
$arr=array('cow'=>'black','feet'=>4);
$encoded=json_encode($arr);
$encoded is now {"cow":"black","feet":4}, which JavaScript can work with. To send this to a page do
header('Content-Type: application/json');
echo $encoded;
header has to happen before you output anything to the page, even a space or blank line, or PHP will give an error.
After generating the data as a PHP array, to output it to JS on the initial page load, you can print it out as the following. Not you don't need to output a special header in this case; it's part of your normal text/html document. The header is for an Ajax return.
<?php
$json_data=json_encode($your_array);
?>
<script>
var an_obj=<?php echo $json_data;?>;
</script>
4 Comments
Use datatype:"json" for data and datatype:"script" to set the data type for your ajax calls.
On the servers side set content-types to application/json and application/javascript , respectively.