简体   繁体   中英

Synchronize text area in html

I am creating a simple web application in which whatever the client types on textarea field also appears on the server side textarea field at the same time.

Imagine it as 2 tabs In one tab user writes on text area and on the other tab user sees the whatever the user has typed at the same time.

Below is the two jsp files code snippet

client.jsp

 <%
code=request.getParameter("code_area");
out.print(code);
        try
        {

        File file=new File("code");
        if(file.exists())
        {
        BufferedWriter bw=new BufferedWriter(new FileWriter(file));
        bw.write(code);
        bw.close();

        }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        %>
<form action="client.jsp">
<textarea name="code_area"> <%=code%> <textarea>
</form>

server.jsp

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Server</title>
    <%@page import="java.io.*"%>
    <script>
        setTimeout("location.reload(true);",1000);
       </script>
</head>
<body>

    <%
        InputStreamReader reader=new InputStreamReader(new FileInputStream("code"));
        BufferedReader in=new BufferedReader(reader);
        String s;
        while((s=in.readLine())!=null)
        out.print(s);
        %>

</body>
</html>

In other Words whatever the user types on the textarea field in the client side appears on the server side at the same time.

The solution that i thought for this problem ..

I created a common file so that whatever user types on textarea in client gets saved in the file and the server side reads from the text-file at the same time.

But sadly i am not able to code it..Because of the problems i am facing in this ..

Everytime i save a file the cursor in the textarea gets to the beginning of the line which i dont want to happen...?

In order to save the data into text file i need to click on submit button ...Auto submit which i tried from this example http://www.formget.com/javascript-auto-submit-form/# is not working ....

Can somebody help me to tackle this problem ?? Any help would be highly appreciated ...

My new understanding (through comments) of the question is... There is a teacher who wants to see all the imputs of the students in real time, each student has 1 input area and the teacher has an display of each students input but can not edit them.

We will create 2 HTML documnet sand 2 PHP APIs. The first HTML document is for the student to enter their name and then a text area for them to enter an answer. The second HTML documnet will be for the teacher to view all the answers. The first API will be for the students to submit their answer (after each keypress ~real time). And the second API will be for the teacher to retrieve all the students answers (with a small refresh interval to simulate real time without having to use WebSockets).

Also you should create a directory/folder within this directory/folder named "answers" and if you are are Mac/Linux give permissions 0777 to the "answers" directory/folder.

Student.html

<html>
<head>
  <title>Student</title>
  <script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
  <script>
    $(function () {
      $("#answer").on("keyup", function (e) {
        $.post("sendAnswer.php", {name: $("#name").val(), answer: e.target.value}, function(){console.log(arguments)});
      });
      $("#name").on("blur", function(e){
        if(e.target.value.length>0)
          $("#answer").attr("disabled", false);
      });
    });
  </script>
</head>
<body>
  <label for='name'>Who are you?</label>
  <input type='text' id='name' Placeholder='Name' />
  <br><br>
  <textarea id='answer' placeholder='Answer' disabled></textarea>
</body>
</html>

Teacher.html

<html>
<head>
  <title>Teacher</title>
  <script src='http://code.jquery.com/jquery-2.1.1.min.js'></script>
  <script>
    $(function(){
      refresh_answers();
      window.setInterval(refresh_answers, 500); // Refresh Every 500ms (0.5 seconds)
    });
    function refresh_answers(){
      $.get("getAnswers.php", function(x){
        x = JSON.parse(x);
        var s = ""; // HTML string
        for(var i=0;i<x.length;i++){
          s+="<div><span class='name'>"+x[i].name+"</span><span class='answer'>"+x[i].answer+"</span></div>";
        }
        $("#answers").html(s);
      });
    }
  </script>
  <style>
    #answers div {
      display: inline-block;
      width: 256px;
      height: 256px;
      border: 1px solid black;
      margin: 16px;
    }
    #answers .name {
      display: block;
      width: 256px;
      height: 56px;
      text-align: center;
      font-size: 25px;
      line-height: 56px;
      font-weight: 700;
      border-bottom: 1px solid black;
    }
    #answers .answer {
      display: block;
      padding: 16px;
      font-size: 14px;
    }
  </style>
</head>
<body>
  <div id='answers'></div>
</body>
</html>

sendAnswer.php

<?php
  file_put_contents(dirname(__FILE__)."/answers/".$_POST['name'].".txt", $_POST['answer']);
?>

getAnswers.php

<?php
  $answers = glob(dirname(__FILE__)."/answers/*");
  $answers_array = array();
  foreach($answers as $a){
    $answer = array();
    $answer['answer'] = file_get_contents($a);
    $name = explode("/", $a);
    $name = array_pop($name);
    $name = str_replace(".txt", '', $name);
    $answer['name'] = $name;
    array_push($answers_array, $answer);
  }
  print_r(json_encode($answers_array));
?>

This can be done with WebSockets but that's way more complicated to set up, but it would be more proper and faster.

For an easy solution (without WebSockets), what you need to do is send an ajax POST request to the server every time the key is pressed, this might be really slow but it should work. Here I will be using jQuery on the client side and PHP on the server side.

HTML

<input id='input' />

JavaScript / jQuery

// After DOM ready
$(function(){ 
  // When a character is entered in the input
  $("#input").on("keyup", function(e){ 
    // Send the inputs value to the server
    $.post("saveInput.php" {text: e.target.value});
  });
});

PHP (saveInput.php)

<?php
    file_put_contents("input.text", $_POST['text']);
?>

This should save their input into a text file called input.txt on the server every time they enter a character in the input.

Take a look at this plugin I think it will do what you want:

https://togetherjs.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM