-1

So I have a live chat, and when the user clicks the button, this function should kick into action and insert it into the database and into the HTML conversation section. The first problem is that if i use dataType: "json" , then it enters the AJAX error case instead of success. But if I pull it out, like below, it enters the success case. But here comes the second problem: only the first alert is displayed, and if I try to alert the response, it doesn't show anything (+neither the alert('yes') is displayed).

function sendMessage(to_user_id) {
    message = $(".message-input input").val();
    $('.message-input input').val('');
    if($.trim(message) == '') {
        return false;
    }
    $.ajax({
        url:"chat_action.php",
        method:"POST",
        data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
        success:function(response) { 
            alert('no'); 
            var resp = JSON.parse(response);            
            $('#conversation').html(resp.conversation);             
            $(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
            alert('yes');
        },
    }); 
}

EDIT1:

It might be useful to understand my files: I have index.php which contains the actual chat. When the send button is clicked, it accesses the chat.js file that contains the script above. Then, this is the part of chat_action.php that deals with it and passes it further to Chat.php.

chat_action.php

session_start();
include ('Chat.php');
$chat = new Chat();
if($_POST['action'] == 'insert_chat') {
    $chat->insertChat($_POST['to_user_id'], $_SESSION['userid'], $_POST['chat_message']);
}

Chat.php

<?php
class Chat{
    private $host  = 'localhost';
    private $user  = 'root';
    private $password   = "";
    private $database  = "chat_demo";      
    private $chatTable = 'chat';
    private $chatUsersTable = 'chat_users';
    private $chatLoginDetailsTable = 'chat_login_details';
    private $dbConnect = false;
    public function __construct(){
        if(!$this->dbConnect){ 
            $conn = new mysqli($this->host, $this->user, $this->password, $this->database);
            if($conn->connect_error){
                die("Error failed to connect to MySQL: " . $conn->connect_error);
            }else{
                $this->dbConnect = $conn;
            }
        }
    }
public function insertChat($reciever_userid, $user_id, $chat_message) {     
        $sqlInsert = "
            INSERT INTO ".$this->chatTable." 
            (reciever_userid, sender_userid, message, status) 
            VALUES ('".$reciever_userid."', '".$user_id."', '".$chat_message."', '1')";
        $result = mysqli_query($this->dbConnect, $sqlInsert);
        if(!$result){
            return ('Error in query: '. mysqli_error($this->dbConnect));
        } else {
            $conversation = $this->getUserChat($user_id, $reciever_userid);
            $data = array(
                "conversation" => $conversation         
            );
            echo json_encode($data);    
        }
    }
    public function getUserChat($from_user_id, $to_user_id) {
        $fromUserAvatar = $this->getUserAvatar($from_user_id);  
        $toUserAvatar = $this->getUserAvatar($to_user_id);          
        $sqlQuery = "
            SELECT * FROM ".$this->chatTable." 
            WHERE (sender_userid = '".$from_user_id."' 
            AND reciever_userid = '".$to_user_id."') 
            OR (sender_userid = '".$to_user_id."' 
            AND reciever_userid = '".$from_user_id."') 
            ORDER BY timestamp ASC";
        $userChat = $this->getData($sqlQuery);  
        $conversation = '<ul>';
        foreach($userChat as $chat){
            $user_name = '';
            if($chat["sender_userid"] == $from_user_id) {
                $conversation .= '<li class="replies">';
                $conversation .= '<img width="22px" height="22px" src="userpics/'.$fromUserAvatar.'" alt="" />';
            } else {
                $conversation .= '<li class="sent">';
                $conversation .= '<img width="22px" height="22px" src="userpics/'.$toUserAvatar.'" alt="" />';
            }           
            $conversation .= '<p>'.$chat["message"].'</p>';         
            $conversation .= '</li>';
        }       
        $conversation .= '</ul>';
        return $conversation;
    }
private function getData($sqlQuery) {
        $result = mysqli_query($this->dbConnect, $sqlQuery);
        if(!$result){
            die('Error in query: '. mysqli_error($this->dbConnect));
        }
        $data= array();
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $data[]=$row;            
        }
        return $data;
    }
    public function getUserAvatar($userid){
        $sqlQuery = "
            SELECT avatar 
            FROM ".$this->chatUsersTable." 
            WHERE userid = '$userid'";
        $userResult = $this->getData($sqlQuery);
        $userAvatar = '';
        foreach ($userResult as $user) {
            $userAvatar = $user['avatar'];
        }   
        return $userAvatar;
    }   
}

EDIT2:

From the console:

chat.js:106

index.php:1 Uncaught SyntaxError: Unexpected end of JSON input

at JSON.parse (<anonymous>)
at Object.success (chat.js:107)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Popescu Ion
  • 142
  • 10
  • 1
    Sounds like the response is invalid json. What does `response` actually look like? – charlietfl Sep 28 '19 at 16:40
  • It seems like you're response isn't valid json. – Musa Sep 28 '19 at 16:40
  • That was my guess too, but idk why it isn't – Popescu Ion Sep 28 '19 at 16:47
  • Could you let us know what is the output of `console.log(response)`. Also please check your console for any error messages. Maybe also show us how you prepare the response on the server. – Dharman Sep 28 '19 at 16:47
  • Log it to console and post what it looks like. Can also inspect the actual request in dev tools network and copy the response body from there – charlietfl Sep 28 '19 at 16:50
  • [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Sep 28 '19 at 16:59
  • Please also provide output of `console.log(response)`. The error message is not as useful as that output. – Dharman Sep 28 '19 at 17:00
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Sep 28 '19 at 17:01
  • I would recommend that you look into a nice PHP tutorial first. Try something like https://phpdelusions.net At the moment your code has many mistakes, which look like are the outcome of a bad PHP tutorial. – Dharman Sep 28 '19 at 17:02
  • well, it wasn't really my code, i just looked for a live chat and i downloaded one that didn't actually work. so i'm trying to fix it :)) – Popescu Ion Sep 28 '19 at 17:05
  • I would recommend to throw it away. It is pretty bad. You won't learn anything from it. Write your own one, but read about PHP first. – Dharman Sep 28 '19 at 17:14

1 Answers1

0

you try to parsing not valid json, in your js maybe try this:

function sendMessage(to_user_id) {
    message = $(".message-input input").val();
    $('.message-input input').val('');
    if($.trim(message) == '') {
        return false;
    }

    $.ajax({
        url:"chat_action.php",
        method:"POST",
        data:{to_user_id:to_user_id, chat_message:message, action:'insert_chat'},
        success:function(response) { 
            alert('no');
            try {
                var resp = JSON.parse(response);            
                $('#conversation').html(resp.conversation);             
            } catch(e) { alert(e) }

            $(".messages").animate({ scrollTop: $('.messages').height() }, "fast");
            alert('yes');
        },
    }); 
}
anon
  • 361
  • 4
  • 8