-1

When I send an ajax post request to my getMessages.php file it doesn't return anything.

I've tried manually setting the array values and printing them in the console and that seems to work.

getMessages.php

<?php

require_once "mysqli.php";

$data = array();

if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
    $username = $_SESSION["username"];

    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time 
        FROM messages 
        WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470' 
        UNION 
        SELECT msg_startuser, msg, time 
        From messages 
        WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}' 
        order by time;
    ");

    while ($row = mysqli_fetch_array($result)) {
        $data['startuser'] = $row['msg_startuser'];
        $data['msg'] = $row['msg'];
    }
}

echo json_encode($data);
exit;
?>

js ajax

function getChat() {

    $.ajax({
        url: 'getMessages.php',
        type: 'POST',
        data: {getChat: 'yes'},
        dataType: 'JSON',
        success: function(data) {
            // testing
            console.log(data.startuser, data.msg);
        }

    })

}

I want it to print out in the console for testing.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Bean
  • 3
  • 2
  • 1
    May or may not bee the root of the problem, but you don't seem to be starting your session. – Patrick Q Apr 10 '19 at 21:16
  • 1
    **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](http://php.net/manual/en/pdo.prepared-statements.php) or by [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). – Dharman Apr 10 '19 at 21:17
  • 1
    Note: A lot of problems can be detected and resolved by [enabling exceptions in `mysqli`](https://stackoverflow.com/questions/14578243/turning-query-errors-to-exceptions-in-mysqli) so any mistakes made aren’t easily ignored. Many return values cannot be ignored, you must pay attention to each one. Exceptions don’t require individual checking, they can be caught at a higher level in the code. – tadman Apr 10 '19 at 21:23
  • Are you there @Bean or is this just a hit-and-run? – Patrick Q Apr 10 '19 at 21:27
  • 1
    I'm here. I forgot to start the session. – Bean Apr 10 '19 at 21:29

4 Answers4

0

data is overwritten in the loop again and again, I guess you would like to do something like this:

$x = 0;
while ($row = mysqli_fetch_array ($result)) {
        $data[$x]['startuser'] = $row['msg_startuser'];
        $data[$x]['msg'] = $ row['msg'];
        $x++;
}
  • Just use `$data[] = [ 'startuser' => $row['msg_startuser'], 'msg' => $row['msg' ]`. The `$x` is pointless and easy to mess up in a bad way. It's also not clear how `$data` ended up as `$ data` with a mysterious and confusing space. – tadman Apr 10 '19 at 21:21
  • 2
    This wouldn't explain "it doesn't return anything", it would only explain the case of fewer results (one) than expected. – Patrick Q Apr 10 '19 at 21:23
  • I think that this is not the answer anyway, because it look like OP didn't want the loop at all, as they seem to be fetching a unique record. – Dharman Apr 10 '19 at 21:23
  • @Dharman There's no `LIMIT` in the query, so this could return any number of records. – tadman Apr 10 '19 at 21:24
  • @tadman True, it could be either way, but nonetheless the answer looks more like a comment than the solution to a problem. – Dharman Apr 10 '19 at 21:25
0

Ooops!

I forgot to start the session!

Thanks PatrickQ!

Bean
  • 3
  • 2
0

This will solve the problem since you are returning response as objects

An Updates:

You will need to initialize session

and data parameters for an array should be inside the the if statements

Try code below

<?php

require_once "mysqli.php";
session_start();

if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
    $username = $_SESSION["username"];

$data = array();


    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time 
        FROM messages 
        WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470' 
        UNION 
        SELECT msg_startuser, msg, time 
        From messages 
        WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}' 
        order by time;
    ");

    while ($row = mysqli_fetch_array($result)) {
         $startuser = $row['msg_startuser'];
        $msg = $row['msg'];

$data = array("startuser" =>$startuser, "msg" =>$msg);
    }


echo json_encode($data);
exit;

}
?>

so in ajax console. this line of code will work fine

console.log(data.startuser, data.msg);
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
0

Hi you can try this way:

The php script :

<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
  if (isset($_POST["endUser"]) &&  isset($_POST["action"])) {
  $case = $_POST["action"];
  $endUser = $_POST["endUser"];
  $username = $_SESSION["username"];
  switch (case) {
    case 'getChat':
    $result = mysqli_query($conn, "SELECT msg_startuser, msg, time
        FROM messages
        WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
        UNION
        SELECT msg_startuser, msg, time
        From messages
        WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
        order by time;
    ");

    while ($row = mysqli_fetch_assoc($resultado)) {
        if (isset($row['msg_startuser']) && isset($row['msg'])) {
          $temp = array(
            "user"=>$row['msg_startuser'],
            "msg"=>$row['msg']
          );
        }
        $data[] = $temp;
    }
    echo json_encode($data);
      break;
  }
  }
}else {
  echo "error-403";
}
 ?>

The javascript :

 function getChat() {

    return $.ajax({
         url: 'getMessages.php',
         type: 'POST',
         data: {action: 'getChat',endUser:'mariokiller470'},
         dataType: 'JSON'
     })

 }

getChat()
.done(function(response){
  console.log(response);
})

Hope it Helps

stan chacon
  • 768
  • 1
  • 6
  • 19