Hendrik Jan
Hendrik Jan

Reputation: 4908

How to include PHP generated data in Dart (no Ajax)

I currently have a website using PHP (Laravel) on the server and Javascript in the client. Now I'd like to replace the Javascript with Dart.

On the current webpage, I inject some data into the Javascript like this:

<script>
    var mydata = <?php echo $mydata; ?>;
    /* now do something with mydata */
</script>

My question is: how do I rewrite this to Dart?

My first take would be:

<script type="application/dart">
    main() {  
        var mydata = <?php echo $mydata; ?>
        /* now do something with mydata */
    }  
</script>

But this approach makes it impossible to generate Javascript code with dart2js since there is dynamically generated code included in the Dart code.

I can of course use an Ajax request, but I choose to place the generated data in the Javascript code because that makes one less HTTP request, making the webpage load faster.

So how would I go about injecting PHP generated data into Dart, without using a HTTP request while still being able to use dart2js?

Upvotes: 2

Views: 277

Answers (2)

Hendrik Jan
Hendrik Jan

Reputation: 4908

Another solution to my own question is this:

<script type="application/json" id="json-data">
    <?php echo json_encode($myData); ?>
</script>

and import this in Dart like:

void main() {
    var myData = JSON.decode(querySelector('#json-data').text);
}

Upvotes: 2

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76303

The simplest solution is to generate datas in JS like you already do and read them from Dart with dart:js. Thus you will have to compile with dart2js only one time.

In your file.php :

<script>
    var myDatasAsJsonString = "<?php echo $myDatasAsJsonString; ?>";
</script>

In your Dart file :

import 'dart:js' as js;
import 'dart:convert' show JSON;

main() {
  final myDatasAsJsonString = js.context['myDatasAsJsonString'];
  final myDatasAsJson = JSON.decode(myDatasAsJsonString);
  /* now do something with mydata */
}

Upvotes: 2

Related Questions