1

I have a text-area which saves the data in my database every-time the user hits a key or writes inside the text-area . My problem is that when i want to show a success message like "saved" in a <p> it repeats itself every-time someone hits a key, i want it to repeatedly show the same message under but only one time.

If possible may remove the "saved" message on success after 10 seconds.

This is what i mean:
I want to remove this "LAGRET"

HTML:

<div class="form-group">
     <label for="comment">Kommentar:</label>
     <textarea class="form-control" rows="5" id="comment" name="comment"></textarea>
  <p name="message" id="message"></p>

jQuery:

$("#comment").keyup(function (){
    var isTyping = $('#comment').val();
    var data = 'result=' + isTyping;

    $.ajax({
        type: 'POST',
        url: "commentsave.php",
        data: data,
        cache: false,
        success: function(html){  
           $('#message').append('Saved');

        }
    });
});

PHP:

$name = $_POST['result'];
echo $name;

Thank you very much, dont need you to code for me but just guide me :)

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Asim
  • 936
  • 2
  • 10
  • 29
  • 4
    Various concerns with this approach aside from your issue. This is going to fire potentially frequently. You may want to debounce this logic so you are not firing for *every* key. Also what if the key was like shift? Or another key that didn't change the value (arrow keys are common)? there is an 'input' event that ignores those. Secondly, what if I paste something in there? It's an outlier, but your logic as wouldn't handle for it. – Taplar Aug 04 '17 at 19:23
  • 4
    That's way too much AJAX requests. Delay AJAX request for a second or two, if user decides to not type anymore, then send the AJAX request. [Answer to this issue](https://stackoverflow.com/questions/1909441/how-to-delay-the-keyup-handler-until-the-user-stops-typing). – Anis Alibegić Aug 04 '17 at 19:24
  • 1
    I agree with both of you, still a learner and now i learned something new. Ill add a delay for few seconds the answer by Alive to die will anyway show if the message was saved or not, i remove the message "saved" after a few seconds also so the user wont be confused if its saved or not. Ill just set a delay right before ajax request right. Thanks both of you – Asim Aug 04 '17 at 19:39

1 Answers1

5

Change:-

$('#message').append('Saved');

to:-

$('#message').html('Saved');

Note:- append() added the new data into the existing-one inside an element, that's why multiple successful messages shown.

While html() will remove old data from element first and then add new-one. So no-repetition will happen.

Please try to read every comment under your post and try to implement them for improvement.Specially not sending ajax call on each key-up. It will broke your system at-some point of time.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98