0

I am trying to make a very simple php chat for my website with CodeIgniter and Ajax. The messages are saved in a html file, not in a database table. Whenever I click the send button, the page refreshes, even though it's not supposed to and I don't know what's wrong.

Here is my controller code:

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;
    }
}

Part of my view:

<div id="chatbox"><?php echo $message; ?></div> <!-- this is the div where the messages are displayed -->

<-- 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>

The javascript

<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>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
eri
  • 109
  • 3
  • 9
  • wha'ts the error ? have check browser's console? – YVS1102 Oct 17 '16 at 09:27
  • There's no error, but when I click the send button , the page refreshes and it shouldn't , because of Ajax. There must be something wrong with my Ajax code, but I don't know what is it. – eri Oct 17 '16 at 09:35
  • var postData = $(#message).serializeArray(); #message in quotes – Rijin Oct 17 '16 at 09:49
  • Doesn't make any difference. – eri Oct 17 '16 at 09:53
  • Well actually it makes a Huge difference, cause even though it aint working now, that's one of the things that will make it not work, when everything else is fixed! – TimBrownlaw Oct 17 '16 at 11:18

3 Answers3

1
  1. var postData = $(#message).serializeArray(); should be:
    var postData = $("#message").serializeArray();
  2. If issue still not get resolved then try to debug by putting alert() or console.log() before e.preventDefault() and then debug your js code.
    For example alert('dummy text for debug');
George Kagan
  • 5,913
  • 8
  • 46
  • 50
himeshc_IB
  • 853
  • 4
  • 10
0

Well actually you really do have a few errors. You are just not looking at them. When you are performing anything JQuery/Javascript related you need to be able to view what is going on.

Look up how to debug using your browser

Personally, I like to you use firefox with the plugin called firebug.

So I have taken your code and simplified it ( I wont comment about the rest of the php) , found the mistakes, fixed them and I've had a little play with it to help demonstrate a couple of things. There are many more to learn...

But so you don't end up tearing your hair out, this is what I came up with to debug this.

The Controller

class Chat_con extends CI_Controller {

    public function __construct() { // This didn't have any __ at all
        parent::__construct(); // error here only one _ not two __
        $this->load->helper('url');
    }

    public function index() {
        $d['info']    = 'Dummy Info';
        $d['message'] = 'What are you going to say?';
        $this->load->view('chat_con_view', $d); //
    }

    /**
     * Process the AJAX Call and send back an HTML Response
     *
     */
    public function write_conv() {
        echo "I said " .$this->input->post('usermsg');
    }
}

The View

<div id="chatbox">
    <?php echo $message; ?>
</div>

<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>

<script src="<?= base_url(); ?>assets/js/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#message").submit(function (e) {
            console.log("The Submit button was pressed - that is a good sign.");
            e.preventDefault();
            var postData = $('#message').serializeArray();
            var formActionURL = $(this).attr("action");
            console.log("postData = " + JSON.stringify(postData));
            console.log("formActionURL = " + formActionURL);
            $.ajax({
                url: formActionURL,
                type: "POST",
                data: postData,
            }).done(function (data) {
                $('#chatbox').html(data);
                alert("success");
            }).fail(function () {
                alert("error");
            }).always(function () {
                $("#submitmsg").val('submit');
            });
        });
    });
</script>

PS. Please compare this against what you had so you can see what mistakes you had made and ask yourself, "why weren't they leaping out of my screen at me?" (I like to be overly dramatic at times).

There's more I can say, but hopefully this will show you how to at least debug something like this, and remember to go and find out how to use your browsers developers console. It will help in every way.

Cheers.

Community
  • 1
  • 1
TimBrownlaw
  • 5,457
  • 3
  • 24
  • 28
  • When you name things, its ok to use your big words... Chat_controller instead of Chat_conv for instance... Call it what it is! – TimBrownlaw Oct 17 '16 at 11:16
  • Thanks for the answer. There's a problem with this line. $('#chatbox').html(data); It creates a div inside the div. So, it's like a chatbox inside a chatbox. – eri Oct 17 '16 at 11:44
  • Well the sample code I provided doesn't. Are you using that or your code? – TimBrownlaw Oct 17 '16 at 11:56
0

this is working for me, check out

  $(document).ready(function() {
    $("#message").submit(function(e) { 
       e.preventDefault();
    var postData = $(this).serialize();
    var formActionURL = $(this).attr("action");
    $.ajax({
        url: formActionURL,
        type: "POST",
        data: postData,
     }).done(function(data) {
        console.log(data);
     }).fail(function() {
        alert("error");
     }).always(function() {
        $("#submitmsg").val('submit');
    });
});
});

html:

   <form name="message" id="message"action="demo.php" method='post'> // edit ur form action properly here
<input name="usermsg" type="text" id="usermsg" size="63" /> 
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />

Umakant Mane
  • 1,001
  • 1
  • 8
  • 9