0

i'm creating a webchat app and i have a problem - i want to send a post with message from user and add it to database, but i don't want to reload my page, i've done something like that, but it is not working:

file index.php:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 setInterval(function () {
         $("#chat-content").load('chat.php');
    },10);

    $("#submit").click(function(){  
        var clientmsg = $("#message").val();
        $.post("chat.php", {text: clientmsg});  
        $("#message").attr("value", "");
        return false;
    });
</script>
</head>
<body>
<div id="chat-content">
</div>
</body>
<form method="post" id="messageform">
<input type="text" id="message" name="message"></input>
<input id="submit" name="sumbit" type="submit" value="Send" />
</form>

File chat.php:

<?php include('db.php');
$query = "SELECT * FROM `czat`;";
$result = $con->prepare($query);
$result->execute();
$count = $result->fetchColumn();
if($count > 100){
    $query = "TRUNCATE `czat`;";
    $result = $con->prepare($query);
    $result->execute();
}

$query = "SELECT * FROM `czat` ORDER BY id ASC LIMIT 10;";
$result = $con->prepare($query);
$result->execute();
while($row = $result->fetch()){
        echo $row["nazwa"].' - '.$row["tresc"].'<br>';
}

if(isset($_POST['text'])){
    $text = $_POST['text'];
    $query = "INSERT INTO `czat` (`id`, `nazwa`, `tresc`) VALUES (NULL, 'dd', '$text');";
    $result = $con->prepare($query);
    $result->execute();
}
?>

db.php is a standard connection to db.

Kizbo
  • 51
  • 2
  • 10

3 Answers3

0

You must use ajax. Ajax provides asynchronous data communication.

For example, you can send your datas (POST or GET) from the client side to the server side. You use the datas which came from the client side in the server side and return the result to the client side. (The result can be html or json. This decision can change according to your choice.)

This is a sample ajax script.

var messageText = $("#message").val();
messageText = messageText.trim(); 
$.ajax({ 
    url : "chat.php", 
    type: "POST", 
    data : {text : messageText} , 
    success: function(data, textStatus, jqXHR) { 
      console.log(data);// You can see the result which is created in chat.php
    },
    error: function (jqXHR, textStatus, errorThrown) {
      console.log(textStatus);// if there is an error
    }
});
mehfatitem
  • 147
  • 1
  • 12
  • OP is already using ajax ... `$.post` is a convenience method for `$.ajax` – charlietfl May 01 '17 at 02:08
  • But I don't think so He knows about Ajax using. That's why , I explained the Ajax structure and gave the little Ajax script. Because in the chat.php , there is no result in order to return the view side. – mehfatitem May 01 '17 at 09:23
  • I did as you saying, but there is no result still, my code for function looks like this: https://pastebin.com/vk6g6U2W Ty for explanation with ajax :) – Kizbo May 01 '17 at 10:19
0

because your submit button is within a form, the default action of the button is POST to the 'action' attribute defined in your form element (in this case not defined in form, it will POST to current page).

You need to preventDefault() for your javascript

$("#submit").click(function(event){  
        event.preventDefault();
        var clientmsg = $("#message").val();
        $.post("chat.php", {text: clientmsg});  
        $("#message").attr("value", "");
        return false;
    });
Nick Li
  • 312
  • 2
  • 12
  • Thank you for advice with preventDefault, but it is not working :/ i included my code in post above if you want to see – Kizbo May 01 '17 at 10:22
  • In which case you need to provide more detail. In fact, your php send nothing out after receiving a POST. What do you mean by it does not work? No data being sent through Ajax? Ajax sent but the page refresh? Th e message remain in input after submit button is clicked? – Nick Li May 01 '17 at 10:38
  • I mean, i want to execute this line of code after the POST is received: https://pastebin.com/8phtaRk9 – Kizbo May 01 '17 at 12:36
  • and... you haven't isolate what your problem is and I cannot help you...does your ajax send anything out? (if using chrome, press F12, network and look at XHR, any POST from your page?). If it was sent, do you receive it in the PHP? (try echo instead of inserting into database). If both exist is your mysql query executed correctly?any errno? (in fact for both PDO and mysqli_stmt, your query string is not formatted properly). You should isolate the problem before asking in here – Nick Li May 01 '17 at 12:43
  • ajax is indeed sending a post, but it looks like script in chat.php is not responding to that at all and i'm unsure why. – Kizbo May 01 '17 at 14:35
  • i worked it out, thank you a lot for your help! – Kizbo May 01 '17 at 15:16
  • Not a problem, Better share your solution as well so others know as well – Nick Li May 01 '17 at 15:18
  • Ah, of course, it was simple - my ajax was good, post was sent, but i had to just assign it to variable in php file – Kizbo May 02 '17 at 13:45
0

Is the post success?(status 200 OK?) Did you try

echo $text;

After defining $text? Do you get a value? Come on, don't just do 1 thing and come back for help, dissect the problem and try to find what's wrong!

Nick Li
  • 312
  • 2
  • 12