mike12255 Posted December 5, 2013 Share Posted December 5, 2013 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? Quote Link to comment https://forums.phpfreaks.com/topic/284540-setinterval-working-on-too-many-functions/ Share on other sites More sharing options...
kicken Posted December 5, 2013 Share Posted December 5, 2013 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; }); }); Quote Link to comment https://forums.phpfreaks.com/topic/284540-setinterval-working-on-too-many-functions/#findComment-1461311 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.