Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <h2>Enter your post here</h2>
    <form>
      <textarea id='user-input-post'></textarea>
      <div>
        <button id=user-post-button>Post</button>
      </div>
    </form>
  </div>
  <div>
    <h2>Below are your posts</h2>
    <ul id='user-post-display'>
      
    </ul>
  </div>
</body>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script>
    /*possible options can be
      'display' - which shows the post in the UI in a unordered list
      'ajax' - which send the post to the server via ajax
    */
    var post_type = 'ajax';
    //the id of the list where the post will be appended
    var list_id = '#user-post-display';
    //the id where the post will be entered
    var post_id = '#user-input-post';
    //the id of the button which triggers some action
    var button_id = '#user-post-button';
    
    //this gets the post from the textarea
    var get_post = function() {
      var post = $(post_id).val();
      return encodeURIComponent(post);
    };
    
    //this appends the post to the list
    var append_post = function() {
      var post = get_post();
      var html_string = '';
      if (post) {
         html_string = '<li>' + post + '</li>';
        $(list_id).append(html_string);
      }
    };
    
    //this sends the post via ajax and triggers callbacks
    var send_post = function() {
      var post = get_post();
      var post_created_on = Date.now();
      var url = 'dummy_url_for_posting';
      $.ajax({
        method: 'POST',
        url: url,
        data: { data: {
          post: post,
          post_created_on: post_created_on
        }}
      })
        .done(function() {
          window.alert('post success');
        })
        .fail(function() {
          window.alert('post fail');
        })
        .always(function() {
          window.alert('post triggered');
        });
    }
    
    //main function which is the entry point
    var main = function() {
      $(button_id).on('click', function() {
        event.preventDefault();
        debugger;
        if (post_type === 'display') {
          append_post();
        } else if (post_type === 'ajax') {
          send_post();
        }
      });
    };
    
    //triggers the main function
    main();
    
  </script>
</html>
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers