0

Good evening SO community,

I'm trying to build a global chat system for my network of websites. In other words, a staff member can log in to www.myadminswebsite.com and check the live chat systems from all of our other external sites. I have the system working fairly well, except for the fact that the page is refreshing every time a user submits a new message. Is there something I can do to avoid refreshing the page to submit a message? Currently, I'm using an HTML form which posts to itself, then the page checks to see if the $_POST["var"] exists, then writes to the IM log file.

Code From HTML Form

<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'>
    <input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
    <input type='submit' value='Send'>
</form>

Function to Process POST

if (isset($_POST['newMSG'])) {
    $wHandle = fopen($lFile, "a");
    fwrite($wHandle, "[CUSTOMER] " . $_POST['newMSG'] . "\n");
    fclose($wHandle);
}

This does what I need it to do, other than refreshing the page. Please let me know if you need any more information or if you have any ideas!

Thanks in advance,

Tim

Timothy Bomer
  • 504
  • 5
  • 21

3 Answers3

1
<form> 
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
    <input type='submit' value='Send' id="submit">

</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$('#submit').click(function()
{
var message=$("#lcTextInput").val();
    $.ajax({
        url: "msg.php", 
        type:'POST',
        data:
        {
            action: 'addmsg',
            message: message
        },
        success: function(msg)
        {
            $(".li").append(message);
        }               
    });

return false;
});

</script>
Nishant Saini
  • 421
  • 3
  • 13
0

Change your form action to:

<form method='POST' action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
    <input type='submit' value='Send'>
</form>
Matt Altepeter
  • 956
  • 1
  • 8
  • 18
0

$('#submit').click(function()
{
var message=$("#lcTextInput").val();
    $.ajax({
        url: "msg.php", 
        type:'POST',
        data:
        {
            action: 'addmsg',
            message: message
        },
        success: function(msg)
        {
            $(".li").append(message);
        }               
    });

return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form> 
<input type='text' name='newMSG' id='lcTextInput' placeholder='Type a Message'>
    <input type='submit' value='Send' id="submit">

</form>
Nishant Saini
  • 421
  • 3
  • 13