kunz
kunz

Reputation: 1047

Display message without reloading page

My problem is every time i want to show a new message i have to reload this page to show new messages but I wanna show new messages without reloading page can i achieve this from JQuery. Please help me

This part is where the messages are shown

$message_query= mysql_query ("SELECT `from_id`, `message` FROM `messages` WHERE `group_hash`='$hash'"); 
  while($run_message = mysql_fetch_assoc($message_query))
      {
         $from_id = $run_message['from_id'];
         $message = $run_message['message'];
        $user_query = mysql_query("SELECT `username` FROM `users` WHERE    `id`='$from_id'");
  $run_user = mysql_fetch_array($user_query);
  $from_username = $run_user['username'];
                echo "<p><b>$from_username</b><br />$message</p>";// this is the place where the message is displayed
      }

This part is where i click the submit button to send the message

<form method="POST">
        <?php
        if(isset($_POST['message']) && !empty($_POST['message']))
    {
     $new_message = $_POST['message'];
        mysql_query("INSERT INTO `u313495632_test`.`messages` (`id`, `group_hash`, `from_id`, `message`) VALUES ('', '$hash', '$my_id', '$new_message');");
        header('Location: conversation.php?hash='.$hash);
    }

    ?>
    Enter Message :<br/>
    <textarea name="message" rows='4' cols='30'></textarea>
    <br><br>
    <input type="submit" value="send message" />
    </form>

This is how the page looks like

enter image description here

Upvotes: 1

Views: 1464

Answers (2)

seybanks
seybanks

Reputation: 39

//this where your page shows then use this jquery var timeout = setInterval(reloadpage,5000);function reloadpage(){$('#page').load('page.php');} //note that this refreshes the page every five seconds

Upvotes: 0

夢のの夢
夢のの夢

Reputation: 5826

in your script write something like this:

<script>
$(document).ready(function(){
    $('form').submit(function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: "yourPhpFile.php",
            data:{message:$('textarea[name="message"]').val()},
            async:true,
            success: function(result){
                //do something
            }
        });
   });
});
</script>

Upvotes: 1

Related Questions