0

Okay people, what I am trying actually trying to achieve is, to create a chat box something similar to fb without refreshing the page. I have two tables in my database(phpmyadmin) where the first table, i store 2 users chat id(unique) and later save their message in another table so that i will be able to retrieve their chat history just by their unique id.

So I was able to send their Id(unique) by using get method to send the unique ID to the second div and then run through the database using php and display their conversation.

So how can i do it in ajax so that the page does not refreshes guys ? Some guide on that please ? I have been trying to google for it but i cant find a way simply because i do not know ajax much.

The purpose of me wanting it to not refresh the page is because i am using Jquery to hide and show the chat conversation. When the page refreshes, the conversation disappears. Im sorry if my explanation is not on point, hopefully somebody understands my problem and guide me in this :D

So here are my codes ...

This code is in my first div. It basically displays all the users who I have chatted with before...

<div>
    <ul style="list-style-type: none;">
    <?php  
    include 'connectDB.php';
    //retrieve all the message history of yours from the PrivateMessage table
    $query = "SELECT * FROM `messagecheck` WHERE `sender_a` = '$userId' 
            OR `sender_b` = '$userId';";
    $result = mysqli_query($dbconnect,$query);
    if(mysqli_num_rows($result) > 0)
    {   
        //if exist, display the history 
        while($row = mysqli_fetch_assoc($result))
        {   
        ?>
            <a href="Item_v1.php?msgId=<?php echo $row['exist']?>">

            <li style="color:black; width:100%; padding-top:5px" >
                <input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
                <?php 
                //if the sender_a id is not my id, display the name
                //if sender_a is my id, then display sender_b
                //Because we dont want to see our name in the chat History
                if($row['sender_a'] != $userId)
                {
                    $senderName = $row['sender_a'];
                     include 'connectDB.php';
                     $nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
                     $Searchresult = mysqli_query($dbconnect,$nameSearch);
                     $Searchrow = mysqli_fetch_assoc($Searchresult);
                     echo $Searchrow['fName'] ." ". $Searchrow['lName'];
                }
                else
                {
                    $senderName = $row['sender_b'];
                     include 'connectDB.php';
                     $nameSearch = "SELECT `fName`, `lName` FROM `register` WHERE `id`='$senderName';";
                     $Searchresult = mysqli_query($dbconnect,$nameSearch);
                     $Searchrow = mysqli_fetch_assoc($Searchresult);
                     echo $Searchrow['fName'] ." ". $Searchrow['lName'];
                } 
                ?>
            </li>

            </a>
        <?php
        }
    }
    ?>
    </ul>
</div>

So basically when i click the names which will be in the < li > tag, it should be posting the messages in another div(Which is the div below)...

<!-- //Message Content! -->
<div style="width:100%;max-height: 300;border: 2px solid #1F1F1F;overflow: auto;">
<?php 
if($_GET)
{
        $msgId = $_GET['msgId'];
}
if(!empty($msgId))
{
    include 'connectDB.php';
    $collectMsgQuery = "SELECT * FROM `privatemessage` WHERE `existing_id` = $msgId";
    $MsgResult = mysqli_query($dbconnect, $collectMsgQuery);
        if(mysqli_num_rows($MsgResult) > 0)
        {
            while($Msgrow = mysqli_fetch_assoc($MsgResult))
            {
                if($userId == $Msgrow['from_who']){
                ?>  
                    <h4 class="ifMe"><span class="ifMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
                <?php
                }else if ($userId == $Msgrow['to_who']) {
                ?>
                    <h4 class="notMe"><span class="notMeDesign"><?php echo $Msgrow['message'] ?></span></h4>
                <?php
                }
            }
        }
}
?>  
</div>

P.S : I'm not really sure how to work with ajax so that is why i am posting it here. Any help would be great! Thanks in advance ! :D

cakan
  • 2,099
  • 5
  • 32
  • 42
topacoBoy
  • 197
  • 2
  • 4
  • 17
  • If you've not yet tried to work with AJAX this is quite an advanced topic. Look up the [jQuery AJAX](http://api.jquery.com/jquery.ajax/) method and have a go at sending some basic requests and viewing the data you get back, then you might see a path to your end goal. Ask on here if you need more specific help with a certain aspect of the problem. – M1ke Nov 19 '15 at 13:46
  • Ajax means you've got javascript on your page calling another endpoint asynchronously and then doing something with the data from that endpoint. An easy library to get started with is jQuery. – wogsland Nov 19 '15 at 13:47
  • Oh, and also your `$collectMsgQuery` string has an SQL injection vulnerability - anyone can place arbitrary code in your `$_GET['msgId']` variable and execute it on your database. – M1ke Nov 19 '15 at 13:47
  • `$query = "SELECT * FROM messagecheck WHERE sender_a = '$userId' OR sender_b = '$userId';";`... You shouldn't use this... you should use MySQL parameters (prepared statements). – Joshua Bakker Nov 19 '15 at 13:50

1 Answers1

-1

Working with ajax, at the beginning, can be very frustrating. You should start with more simple task, simply to understand what you're working with. Start with something like this, a simple request that send two numbers to the server and then alert the sum

ajax_request.php

<?php
$num1 = isset( $_GET[ "num1" ] ) ? $_GET[ "num1" ]: 0;
$num2 = isset( $_GET[ "num2" ] ) ? $_GET[ "num2" ]: 0;
echo $num1 + $num2;

index.html

    <html>
    <head>
        <script src="jquery-1.11.3.min.js"></script>
        <script>
        $(document).ready(function () {
            $( "#calculate" ).click(function(e) {
                e.preventDefault();
                $.ajax({
                    url: 'ajax_request.php',
                    data: $( "#form" ).serialize(),
                    success: function( data ) {
                        alert( data );
                    },
                    error: function() {
                        alert( "Something went wrong" );
                    }
                });
            });
        });
        </script>
    </head>
    <body>
        <form id="form">
            Num1: <input type="text" name="num1" /><br />
            Num2: <input type="text" name="num2" /><br />
            <input type="submit" id="calculate" />
        </form>
    </body>
</html>

Open index.html (download the jQuery library), fill the two numbers and click the button. You can test the "Something went wrong", simply put a wrong url (ajax_requestx.php instead of ajax_request.php). From here, you can study "ajax" and "jQuery" to understand better how this work.

The concept is this: you stop the form to be sent (e.preventDefault()) and instead send the form in "asyncronous" way, making javascript send the request to the server without changing the page; in the "success" function you can analyze the string sent back from the server and do something with it. All done by javascript

RiccardoC
  • 876
  • 5
  • 10
  • This is not an answer to the question asked, it is a comment. – Wesley Smith Nov 19 '15 at 14:15
  • Pherapse, but I cannot post code in comments and I think it's much more usefull to show the matter this way that simply write "study ajax and jquery" – RiccardoC Nov 19 '15 at 14:16
  • In cases such as that, it might be better to post a comment with a link to an example posted elsewhere like [phpfiddle](http://phpfiddle.org/) , [jsFiddle](http://jsfiddle.net/), [codepen](http://codepen.io/), etc – Wesley Smith Nov 19 '15 at 14:19