Jump to content

Recommended Posts

So ive started taking a crack at learning javascript/ajax and am trying to make a simple chat box. I got this script *almost* working flawless. What I want to do right now is make the script run my function that loads messages every three seconds. I read online about the setinterval function however this makes my post function post the same item multiple times. Also when you first load a page it doesnt show anything in the chat box for three seconds:

    <script>
    	
    	$(document).ready(setInterval(function() {
		$("#messageContainer").load('chat_process.php?a=load');
		
		$("#formsubmit").submit(function() {
			
			$.post('chat_process.php?a=post', $('#formsubmit').serialize(), function (data){
				document.getElementById('Message').value ="Message";
			});
			return false;
			
		});
		
		},3000));
    </script>

Would it be best practice to make another document.ready and place the post call in that without an interval function?

You don't need a separate document ready handler, you just need to limit what happens in your setInterval callback. You only want the setInterval to load messages, so that is the only bit of code that should be in that function. Your form submit handler would go outside of the interval function.

 

$(function(){ ///shortcut for $(document).ready(function(){
   setInterval(function(){
      //Load messages.  This is the only bit which belongs here.
      $("#messageContainer").load('chat_process.php?a=load');
   }, 3000);

   //The submit handler goes here, outside of the interval function (but inside the ready event)
   $("#formsubmit").submit(function() {
      $.post('chat_process.php?a=post', $('#formsubmit').serialize(), function (data){
         document.getElementById('Message').value ="Message";
      });
      return false;
   });
});
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.