Edit: for some reason it seems like its refreshing the page upon hitting the submit button... any ideas?
working on this simple chatroom script using ajax and kohana php framework. I can't seem to get my script working for creating a new user though and I have terrible debugging skills in php and javascript. Anyway I don't know if there's anything else to say.. here's my code:
heres the code for the user class:
class Model_User extends Kohana_Model
{
var $_loaded = false;
var $session = false;
var $username = false;
var $loginkey = false;
function __construct()
{
$this->session = Session::instance();
}
function new_user($username)
{
if($this->username_exists($username))
return false;
$this->username = $username;
$this->generate_key();
return $this->update_db();
}
function username_exists($username)
{
if(DB::select()->from('users')->where('username', '=', $username)->execute()->count()<1);
return false;
return true;
}
//helper methods
private function generate_key()
{
if( ! $username)
return false;
$this->loginkey = md5($username.((int)mt_srand()*1000));
$this->session->set('loginkey',$this->loginkey);
return true;
}
private function update_db()
{
if(DB::insert('users', array('username'=>$this->username, 'loginkey'=>$this->loginkey))->execute())
return true;
return false;
}
}
and heres the code to handle the json request:
public function action_new_user(){
$user = new Model_User();
$json['username_exists'] = "true";
$username = $_POST['username'];
if(isset($username))
{
if($user->username_exists($username))
{
echo json_encode($json);
return;
}
$user->new_user($_POST['username']);
$json['username_exists'] = "false";
}
$this->request->response = json_encode($json);
}
and heres the jquery and html
<div id="chat_entry_errors">
</div>
<form id="new_chat_entry" name="posttest">
<input type="text" name="username" />
<input type="submit" name="submit" value="New User" />
</form>
$(document).ready(function(){
$('#new_chat_entry').submit(function(){
$.post('json/new_user', $('#new_chat_entry').serialize(),
function(data){
if(data.username_exists=='true'){
$('#chat_entry_errors').html('<div class=\"error\">Sorry that username is currently unavailable. Please choose another.</div>');
}
else {
$('#chat_entry_errors').html('<div class=\"error\">Success!</div>');
}
}
);
});
});
Looks like it's submitting the form. Since you don't have an action parameter it would submit to the same page, acting like a refresh. Try adding return false;
to the end of your submit function.
$(document).ready(function(){
$('#new_chat_entry').submit(function(){
$.post('json/new_user', $('#new_chat_entry').serialize(),
function(data){
if(data.username_exists=='true'){
$('#chat_entry_errors').html('<div class=\"error\">Sorry that username is currently unavailable. Please choose another.</div>');
}
else {
$('#chat_entry_errors').html('<div class=\"error\">Success!</div>');
}
}
);
return false;
});
});