Building a chatbox

My project is just for fun, I was able to install a simple comment plugin and I would like to transform it as a chat. Same thing as a comment system but the form could be send via AJAX. But here is my problem, I don’t know how to send it.

I have minimize the code for a very basic test case, no name/email field, just a textarea.

This is my controller :

return function($site, $pages, $page) {
  $alert = null;
  if(get('submit')) {
    $data = array(    
      'comment'  => filter_var(get('comment'), FILTER_SANITIZE_STRING),
      'date' => date('Y-m-d'),
      'time' => date('H:i')
      try {
        $comments = yaml($page->comments());
        $comments[] = $data;
          'comments' => yaml::encode($comments),

      } catch(Exception $e) {
        echo $e->getMessage();

and the template :

<div id="comments">
        <?php foreach($page->comments()->toStructure()->flip() as $comment): ?>
            <span><?php echo $comment->comment() ?></span> 
        <?php endforeach ?>
    <div class="comments_form">
        <h2>Leave a comment:</h2>
        <form id="form" method="post">
            <div class="field">
                <label for="comment">Comment <abbr title="required">*</abbr></label>
                <textarea id="comment" name="comment" placeholder="Comment" required></textarea>
            <input class="btn" type="submit" name="submit" value="Submit">

Now, how can I send the structure entry via AJAX, and in same time, get the comment into the template without reloading the page ? My goal is to send the information instantanely with the submit button

i think you need to use a route rather then a controller, for ajax stuff, like the example in the uniform plugin. I know your not using that but i think the technicalities are similar. Your form is missing an action.

If you want to use Ajax, I’d use a content representation or a route.

In your JavaScript, you listen on the submit button and then call your content representation or your route. The whole procedure is pretty similar to the example in the [load more with Ajax]( cookbook recipe. with the difference that you listen to the submit button instead of the load more button.

You can use the action attribute to pass the URL to listen to, but you could instead also use a data attribute or a hard-coded url in your JS, the action attribute is not required.