richalot
richalot

Reputation: 4821

How to write to an HTML element from the server in Dart

I am trying to learn the basics of server side Dart. When I hit the submit element on the HTML page, the screen is cleared and replaced with "hello." I am trying to keep all elements in place, and put the "hello" in the div place. I have not found any basic documentation on this, so I may be missing a lot here. Is there a straightforward way to do this?

Here is the Server code:

import 'dart:io';

Future main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    8080,
  );

  await for (HttpRequest request in server) {
request.response
  ..write("hello")
  ..close();
  }
}

Here is the HTML:

<form action="http://localhost:8080" method="GET">
<input type="text" id="name" value="name">
<input type="submit" value="submit">
</form>
<div id="output"></div>  // I want the "hello" to go here

Upvotes: 2

Views: 249

Answers (1)

Murtaza Hussain
Murtaza Hussain

Reputation: 4285

It's quite common to build web applications that pull in data from other web applications, initiated by logic that performs HTTP calls to third party services.

lets look at how we can use the inbuilt HttpRequest classes to make HTTP calls to external services.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>A Minimalist App</title>
  </head>

  <body>
     <div id="output">Hi</div>  // I want the "hello" to go here
    <script type="application/dart" src="main.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

main.dart

import 'dart:html';
void main() {
  var response = await HttpRequest.getString('http://localhost:8080')
  querySelector('#output').text = response;
}

For more info visit here

Thanks. :) , hope it helps.

Upvotes: 1

Related Questions