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?

1
  • take a look at the php function json_encode - you can pass multidimensional associative arrays to it. Commented Nov 27, 2010 at 6:31

2 Answers 2

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> 
Sign up to request clarification or add additional context in comments.

4 Comments

.. .what should be the relevant code for the javascript file ?
@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?
... m outputting the variable into the page through javascript .... also m using Ajax to fetch the data Dynamically !
@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?
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.

3 Comments

What is the difference between application/json and application/javascript , respectively ?
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 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.