Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

html - jquery ajax call to php is failing to insert data

I wrote a php code that insert data into the database without refreshing the page. But unfortunately there is a error. Please help me to fix it. The error I got was I can't input any data to the database

Here in the message.php i get the data and post it to the insertmsg.php file using ajax.

messages.php

    <head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $('.sendmsgbutton').click(function (e) {
      e.preventDefault();
      var from_user = $('#from_user').val();
      var to_user = $('#to_user').val();
      var msg = $('#msg').val();
      $.ajax
        ({
          type: "POST",
          url: "insertmsg.php",
          data: {"from_user": from_user,
                 "to_user": to_user,               
                 "msg": msg}
          success: function (data) {
            $('#chatarea')[0].reset();
          }
        });
    });
  });
</script>
</head>

<?php 
$username = $_SESSION['username'];
if (!isset($_SESSION['username']))
{header("Location: login.php");
  die();
}
  $fuck = "yohan";

?>


<div class="main">

<!--  PHP FOR READ THE DATA OF THE QUESTION THAT THE USER CLICKED --> 

<div class="friendslist">
<?php  
if (isset($_GET['id'])) {
        global $con;

        $id = htmlentities(mysqli_real_escape_string($con,$_GET['id']));

        $select = "SELECT * FROM `users` WHERE id='$id'";
        $result = $con->query($select);

        while ($row = mysqli_fetch_array($result)) {
            $name = $row['username'];
            echo "@$name";
}

echo "<div class='chatbox'>
</div>
<div class='sendmsgarea'>
<form method='post' action='' id='chatarea'>
<input type='hidden' id='from_user' value='$username'>
<input type='hidden' id='to_user' value='$fuck'>
<input type='text' class='sendmsgbox' id='msg' required=''>
<input type='submit' class='sendmsgbutton' value='Send'>
</form>
</div>


";



}
    ?>
</div>
</div>

insertmsg.php

<?php
//Database connection
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'mess';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($conn); 

//insert into database
if(!empty($_POST)) {
 $from_user = $_POST["from_user"];
 $to_user = $_POST["to_user"];
 $msg = $_POST["msg"];

 mysqli_query($conn, "INSERT into `messages` (`from_user`, `to_user`, `msg`) values ('$from_user','$to_user','$msg')"); 
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...