up vote 1 down vote favorite

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?

link|flag

80% accept rate
take a look at the php function json_encode - you can pass multidimensional associative arrays to it. – Zevan Nov 27 at 6:31

2 Answers

up vote 4 down vote

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> 
link|flag
@alex ... .what should be the relevant code for the javascript file ? – user522003 Nov 27 at 8: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? – Alex JL Nov 27 at 8:54
@Alex.... m outputting the variable into the page through javascript .... also m using Ajax to fetch the data Dynamically ! – user522003 Nov 27 at 9: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? – Alex JL Nov 27 at 10:00
up vote 1 down vote

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.

link|flag
What is the difference between application/json and application/javascript , respectively ? – user522003 Nov 27 at 6: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 . – user522003 Nov 27 at 6:30
1  
@user522003 regarding the mime type, see stackoverflow.com/questions/477816/the-right-json-content-type – Alex JL Nov 27 at 6:36
@user522003: they are not the same, script objects can be executed via eval() not the same things as json objects. – conqenator Nov 27 at 16:44

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.