Reputation: 341
I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php
and then refresh #cbox
. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php
executes without problems, so it definitely is my ajax script. In addition, getUpdates()
works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>
Upvotes: 2
Views: 42
Reputation: 171679
Several issues:
Your click handler exists before the element it references and is not inside document.ready
. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})
Upvotes: 1
Reputation: 3027
This might be a simple as moving });
from the third line of your script, to just before </script>
so that your function and your ajax call are inside $(document).ready(...
and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.
Upvotes: 1