SUBMIT without refresh
I've been posting different versions of this code all day (sorry!). I'm now trying to have it so when you SUBMIT (by hitting enter), it doesn't refresh the page. I tried setting the submit button as a BUTTON, but that only works when you actually click on it.
I've been doing research, but a lot of my results are outdated JavaScript methods.
These are taken from my HTML markup. Everything else is just the usual html, head, body, and CSS.
<?php
session_start();
if(!isset($_SESSION['id'])){
$_SESSION['id'] = rand(0,100);
}
?>
<div id="room">
<div id="send_cont">
<form id="chat">
<input type="text" id="msg" />
<input type="submit" id="send" value=" " />
</form>
</div>
<div id="messages">
Loading...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var refreshchat = function(){
$.get('ajax.php', function(data) {
$('#messages').html(data);
});
var msgs = document.getElementById('messages');
msgs.scrollTop = msgs.scrollHeight;
}
var getmsgs = self.setInterval(refreshchat,0);
$('#chat').submit(function(){
var msg = $('#msg').val();
$.post("ajax.php", { msg: msg, from: "You" },
function(data) {
$('#messages').html(data);
$('#msg').val('');
var msgs = document.getElementById('messages');
msgs.scrollTop开发者_如何学Go = msgs.scrollHeight;
});
});
return false;
});
</script>
You may want to prevent the default browser behavior with the event object that can be passed to a jQuery event click handler.
Something on the order of:
$('#send').click(function(evt){
evt.preventDefault()
// perform ajax call here...
});
$(document).ready(function() {
var refreshchat = function() {
$.get('ajax.php', function(data) {
$('#messages').html(data);
});
var msgs = document.getElementById('messages');
msgs.scrollTop = msgs.scrollHeight;
}
var getmsgs = self.setInterval(refreshchat, 0);
$('#chat').submit(function() {
var msg = $('#msg').val();
$.post("ajax.php", {
msg: msg,
from: "You"
}, function(data) {
$('#messages').html(data);
$('#msg').val('');
var msgs = document.getElementById('messages');
msgs.scrollTop = msgs.scrollHeight;
});
return false; // <--- needed here...
});
// return false; <--- not in the right place....
});
you can use
$('#submit').click(function(evt){
evt.preventDefault()
// perform ajax call here...
});
or
$('#submit').click(function(evt){
// perform ajax call here...
return false ;
});
精彩评论