I am trying to create a text box and whenever a user enters a message and clicks on send, the ajax should be activated and what’s on insertMessage.php should get triggered. However, whenever i click on send it doesn’t work. here is my chatbox.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user=$_SESSION['userid'];
$sql="SELECT * FROM `users` WHERE `Email`='$user'";
$res= mysqli_query($conn,$sql);
$user=mysqli_fetch_assoc($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>Hi <?php echo $user["FullName"]; ?></p>
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
<p>Send Message To:</p>
<ul>
<?php
$msgs=mysqli_query($conn,"SELECT * FROM users");
while($msg=mysqli_fetch_assoc($msgs))
{
echo '<li><a href="?toUser='.$msg['Email'].'">'.$msg["FullName"].'</a></li>';
}
?>
</ul>
<a href="index.php"><--Back</a>
</div>
<div class="col-md-4">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?php
if(isset($_GET["toUser"]))
{
$user=$_GET["toUser"];
$email=mysqli_query($conn,"SELECT * FROM users WHERE Email='$user'");
$emails=mysqli_fetch_assoc($email);
echo '<input type="text" value='.$user.' id="toUser" hidden/>';
echo $emails["Email"];
}
else{
$email=mysqli_query($conn,"SELECT * FROM users");
$emails=mysqli_fetch_assoc($email);
$_SESSION['toUser']=$emails['Email'];
echo '<input type="text" value='.$_SESSION['toUser'].' id="toUser" hidden/>';
echo $emails["Email"];
}
?></h5>
</div>
<div class="model-body" id="msgBody" style="height:400px; overflow-y:scroll; overflow-x:hidden;">
<?php
if(isset($_GET["toUser"]))
{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Receiver`='".$_SESSION["userid"]."' AND `Sender`='".$_GET["toUser"]."') OR (`Receiver`='".$_GET["toUser"]."' AND `Sender`='".$_SESSION["userid"]."')");
}
else{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Sender`='".$_SESSION["userid"]."' AND `Receiver`='".$_GET["toUser"]."') OR (`Sender`='".$_GET["toUser"]."' AND `Receiver`='".$_SESSION["userid"]."')");
}
while($chat=mysqli_fetch_assoc($chats))
{
if($chat["Sender"]==$_SESSION["userid"])
{
echo "<div style='text-align:right;'>
<p style='background-color:lightblue; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
else{
echo "<div style='text-align:left;'>
<p style='background-color:yellow; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
}
?>
</div>
<div class="model-footer">
<textarea id="message" class="form-control" style="height:43px;max-width:80%;float:left;">
</textarea>
<button id="send" class="btn btn-primary" style="height:70%;float:left;">Send</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#send').on('click', function(e) {
e.preventDefault();
$.ajax({
url:"insertMessage.php",
method:"POST",
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
dataType:"text",
success:function(data){
$("#message").val("");
}
});
e.preventDefault();
});
});
</script>
</html>
and here is my insertMessage.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fromUser=$_POST["fromUser"];
$toUser=$_POST["toUser"];
$message=$_POST["message"];
$output="";
$sql="INSERT INTO `message`(`Sender`, `Receiver`, `Message`) VALUES ('$fromUser','$toUser','$message')";
if($connect->query($sql)){
$output.="";
}
else{
$output.="Error. Please Try Again.";
}
echo $output;
?>
I don’t know what to do i tried to find the issue so much but I couldn’t. I am new to ajax so I don’t know..
3
Answers
Put all your form elements inside a
<form>
in order to receive a data from your$_POST
.Don’t forget to include
method="post"
in your form element, putname="fieldName"
on your input elements (text, button, textarea) and a submit button.I am not sure what your exact problem is but there is one issue in your jQuery code, it takes an object as a value of data, like below :
Replace your semicolon (;) with a comma(,)
Your
data
seems to have issues:So, please change:
To:
Explanation:
Semi colons(
;
)are for closing a statement.And the
fromUser
and others are properties of objectdata
. So, they should be comma separated and it is one statement.Also, as a suggestion:
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
The above field definition should have double quotes(
""
) aroundvalue
.It creates issues(without semi-colons) when there are spaces in our
value
.And
hidden
makes no meaning at all with above, is it oftype="hidden"
or is itclass="hidden"
?