1

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?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • take a look at the php function json_encode - you can pass multidimensional associative arrays to it. – Zevan Nov 27 '10 at 06:31

2 Answers2

4

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> 
JAL
  • 20,237
  • 1
  • 45
  • 63
  • .. .what should be the relevant code for the javascript file ? –  Nov 27 '10 at 08:21
  • @user522003 It gets a bit complex there, depending - are you using ajax to fetch this data dynamically, or outputting this variable into the page to begin with? – JAL Nov 27 '10 at 08:54
  • ... m outputting the variable into the page through javascript .... also m using Ajax to fetch the data Dynamically ! –  Nov 27 '10 at 09:15
  • @user522003 Okay, I've added an example of how to output it into a JS variable. Fetching it with Ajax is a pretty large topic, involving HTML, JS and another PHP file - you may wish to add that as whole new question. Are you using a library such as jQuery? – JAL Nov 27 '10 at 10:00
1

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.

Robin Maben
  • 19,662
  • 16
  • 61
  • 93
  • What is the difference between application/json and application/javascript , respectively ? –  Nov 27 '10 at 06:29
  • I have an array in php named as say edge_id[]. Now how should I define the datatype to send to the client i.e. javascript side . –  Nov 27 '10 at 06:30
  • 1
    @user522003 regarding the mime type, see http://stackoverflow.com/questions/477816/the-right-json-content-type – JAL Nov 27 '10 at 06:36