Ich versuche einen sehr einfachen PHP-Chat für meine Website mit CodeIgniter und Ajax zu machen. Die Nachrichten werden in einer HTML-Datei und nicht in einer Datenbanktabelle gespeichert. Immer wenn ich auf den Senden-Button klicke, wird die Seite aktualisiert, obwohl sie nicht angezeigt wird und ich weiß nicht, was falsch ist. ist hier mein Code: Mein Controller-Code:Wie benutzt man Ajax im Codezeichner?
class Chat_con extends CI_Controller{
function construct(){
parent::_construct();
}
public function index(){
$this->load->model('login_model');
$d['info']=$this->login_model->display_user_data();//this info is sent to view to display the username of the person who is using the chat
$d['message']=$this->read_conv();
$this->load->view('chat_view',$d);
}
function write_conv() {
$this->load->helper('directory');
$this->load->helper('url');
$this->load->helper('file');
$this->path = "application" . DIRECTORY_SEPARATOR . "files"
. DIRECTORY_SEPARATOR;
$this->file = $this->path . "log.html";
$m=$this->input->post('usermsg');
$u=$this->session->userdata('username');
write_file($this->file,"<div class='msgln'>(".date("g:i A").") <b>".$u."</b>: ".stripslashes(htmlspecialchars($m))."<br></div>",'a');
$this->index();
}
function read_conv(){
$this->load->helper('directory');
$this->load->helper('url');
$this->load->helper('file');
$this->path = "application" . DIRECTORY_SEPARATOR . "files"
. DIRECTORY_SEPARATOR;
$this->file = $this->path . "log.html";
$string = read_file($this->file);
return $string;
}
}
Teil meiner Ansicht:
<div id="chatbox">//this is the div where the messages are displayed
<?php echo $message; ?></div>
//this is the form
<form name="message" id="message"action="<?php echo base_url();?
>chat_con/write_conv" method='post'>
<input name="usermsg" type="text" id="usermsg" size="63" /> <input
name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
// Das Skript
<script type="text/javascript">
$(document).ready(function() {
$("#message").submit(function(e) {
e.preventDefault();
var postData = $(#message).serializeArray();
var formActionURL = $(this).attr("action");
$.ajax({
url: formActionURL,
type: "POST",
data: postData,
}).done(function(data) {
alert("success");
}).fail(function() {
alert("error");
}).always(function() {
$("#submitmsg").val('submit');
});
});
}
</script>
wha'ts der Fehler?Haben Sie die Browser-Konsole? – YVS1102
Es gibt keinen Fehler, aber wenn ich auf den Senden-Button klicke, wird die Seite aktualisiert und sollte nicht, wegen Ajax. Es muss etwas mit meinem Ajax-Code nicht stimmen, aber ich weiß nicht, was es ist. – eri
var postData = $ (# Nachricht) .serializeArray(); #Message in Anführungszeichen – Rijin