Restore Structure from Server to Ketcher

Q

How to restore a chemical structure from the Web server to the Ketcher editor?

✍: FYIcenter.com

A

If you want to build a chemical structure editor with the capability to save the structure on the Web server and restore it later to the Ketcher, you should follow steps described below:

1. Using JavaScript to export the chemical structure from the Ketcher editor in "Ketcher" format. It preserves all information about the structure.

2. Using JavaScript to submit the exported structure to the Web server with HTML form.

3. The server script to save the exported structure on the Web server.

4. When the Web page is reloaded, import the saved structure back to the Ketcher editor.

Here is a PHP script that shows you how to implement those steps in a single script.

<html>
<!-- restore-structure.php Copyright (c) FYIcenter.com. All rights reserved. -->
<head>
<title>Restore and Edit Structure</title>
<script>
var ketcher = null;

function restore() {
  frm = document.getElementById("frmKetcher");
  ketcher = frm.contentWindow.ketcher;
  ketcher.setMolecule(document.getElementsByName("Ketcher")[0].value);
}

function save() {
  frm = document.getElementById("frmKetcher");
  ketcher = frm.contentWindow.ketcher;
  ketcher.getKet().then(consumeKetcher, consumeError);
}

function consumeKetcher(result) {
  document.getElementsByName("Ketcher")[0].value = result;
  document.getElementsByTagName("form")[0].submit();
}

function consumeError(result) {
  alert(result);
}
</script>
</head>
<body onload="restore();">
<p>Here is the structure you saved previously. 
You can update and save it again.
</p>

<iframe id=frmKetcher src="/ketcher/index.html"
  style="width: 680px; height: 400px;"></iframe>

<p><button type="button" onclick="save()">
  Save the structure to the server</button>
</p>
<?php
  $structure = "";
  if (isset($_REQUEST["Ketcher"])) {
    $structure = $_REQUEST["Ketcher"];
  } else {
    $structure = file_get_contents("my-structure.ket");
  }

  $structure = htmlspecialchars($structure);
  $html = <<<EOS
<form action="restore-structure.php">
<input type="hidden" name="Ketcher" value="$structure">
</form> 
EOS;
  print($html);
?>
</body>
</html>

Note that the restore() method is called as the "load" event handler on "body" HTML element. This is to wait for the Ketcher editor to be fully loaded, before importing the structure back to the editor.

You can open this PHP script on your local Web server. It will start with an empty editor. But if you create a structure and save it, you will see structure when you open the page again later.

Restore Strucure from Server to Ketcher
Restore Strucure from Server to Ketcher

 

Use Ketcher as JS Library Without UI

Save Structure from Ketcher to Server

Ketcher JavaScript API

⇑⇑ Ketcher - Chemical Structure Editor

2023-10-11, 354🔥, 0💬