Home > OS >  Why AJAX is not sending data to my PHP page?
Why AJAX is not sending data to my PHP page?

Time:09-16

I am trying to make a Messaging App, when i fill the input and click the send button the Success function works but data doesn't get sent to the insertMessage.php Page.

  $(document).ready(function(){
  $("#button_send").on("click", function(){
    $.ajax({
        url:"insertMessage.php",
        method:"POST",
        data:{
          fromUser: $("#fromUser").innerHTML,
          toUser: $("#toUser").innerHTML,
          message: $("#message_text").val()
        },
        dataType:"text",
        success:function(data){
          $("#message_text").val("");
        }
    });
  });
});

insertMessage.php Page:

<?php
session_start();
include 'includes/config.php';

$fromUser = $_POST['fromUser'];
$toUser = $_POST['toUser'];
$message = $_POST['message'];

$message = htmlspecialchars($messgae);

$date_p1 = date("d/m/Y");
$date_p2 = date("h:i:sa");
$date = $date_p1." at ".$date_p2;

$insert_message = "INSERT INTO users_messages (from_user, to_user, message, date_time) VALUES (?,?,?,?)";
$check_insert_message = $db->prepare($insert_message);
$check_insert_message->execute([$fromUser, $toUser, $message, $date]);

?>

CodePudding user response:

Consider the following Snippet.

$(function() {
  $("#buttonSend").click(function() {
    $.ajax({
      url: "insertMessage.php",
      method: "POST",
      data: {
        fromUser: $("#fromUser").html(),
        toUser: $("#toUser").html(),
        message: $("#messageText").val()
      },
      success: function(data) {
        $("#messageText").val("");
      }
    });
  });
});
#sendMessage label {
  display: inline-block;
  width: 80px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sendMessage">
  <div><label>From</label><span id="fromUser">Agent Smith</span></div>
  <div><label>To</label><span id="toUser">Tomas Anderson</span></div>
  <div><label>Message</label><input type="text" id="messageText" /></div>
  <button id="buttonSend">Send</button>
</div>

This should work with your PHP.

I noticed you were switching from Camel Humps to Underscores in your ID Naming convention, it's a better practice to use one or the other. I switched them all to Camel Humps.

Your click event should not need to use .on() unless the elements does not exist in DOM until later. So I changed this to .click() callback.

It was not clear why you were trying to use the innerHTML property. This is not a property of jQuery Objects. So I switch to using .html() which will collect the HTML content of the selected object.

See More: https://api.jquery.com/html/

This method uses the browser's innerHTML property.

  • Related