0

I have a AJAX call that looks like this and I have included the tag as well:

<script>
        $.post("../processor/get_notifications.php",
            {
                id: <?php echo $_SESSION["id"]; ?>
            },
            function(data, status){
               console.log("Data: " + data + "\nStatus: " + status);
            });
</script>

And the .php file looks like this:

    <?php
if(isset($_POST["id"])){
    require '../includes/backbone.php'; //It contains the server information
    $connection = mysqli_connect($server_name, $database_username, $database_password, $database_name);
    $sql = "SELECT user_json FROM users WHERE id = " . $_POST["id"] . "";
    $result = mysqli_query($connection, $sql);
    echo $result;
}

So, I am trying to pass the user_json stored in the database to the page from where the AJAX call is done. But, It shows an internal server error. I guessed that the error was caused as the variable $result may be an object. And when I tried to check if the type of the variable was object using echo gettype($result);, it showed object in the console. So, I tried to change the object to string using three methods out of which none worked:

  • $result = "'" . $result . "'"; //which I was sure wouldn't work
  • $result = (string)$result;
  • $result =json_decode($result); //which didn't make sense. So, How am I supposed to get the object in the page to do something like:

    document.write(object["about"]); or so on?

  • **Warning:** Your code is *highly vulnerable* to **SQL injection**. At some point you'll want to take a look here to learn what that is and how to correct it: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – David Apr 29 '18 at 13:17
  • That's the second step after the project is ready but I am stuck!!! –  Apr 29 '18 at 13:19
  • Studying some mysqli tutorials would help. You need to use one of the `fetch` methods to get data from $result and then json_encode that – charlietfl Apr 29 '18 at 13:22
  • You're effectively asking how to echo the results of your query as JSON, the linked duplicate explains that. However, be aware that there could be a variety of other problems in your code. (1) The aforementioned SQL injection could be causing problems. (2) You hint at an error, but then don't do anything to investigate that error. If you're getting an error, debug it. (3) What you're doing with the resulting data on the client-side may not make sense if it's a complex object. (Its printed string representation might not mean anything.) Etc. – David Apr 29 '18 at 13:23
  • It prints {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} in the console. why is it so? –  Apr 29 '18 at 13:26

0 Answers0