-3

Hi friends am having trouble here, i want to generate this code for notifications in json format so i can convert into html but i get this error: Notice: Undefined variable: result_array in C:\xampp\htdocs\futbolextensive.co.ke\notifications_controller.php on line 70 {"result":null} here is my code

<?php
     //Select all notifications for a given user_id and return in JSON format
       $sql = "select * from notifications";
       $res = mysqli_query($con,$sql);
       $result = array();
       while($row = mysqli_fetch_array($res)) 
        {
           array_push($result,array('id'=>$row[0],'creation_date_time'=>$row[1],
           'view_date_time'=>$row[2],'user_id'=>$row[3],'notification_text'=>$row[4],'is_viewed'=>$row[5]));
        }
        echo json_encode(compact('result'));
        //Here you can format all notifications into well-organized HTML code just like in order to present in nice way
        //it is being returned in JSON format
        exit;
?>

here is the javascript to out put html but is returns json format still

<script>
function show_notifications()
{
  //user_id = 1 First User's Id
  //command = FETCH_NOTIFICATIONS
  var show_notifications_url = "notifications_controller.php?command=FETCH_NOTIFICATIONS&user_id=15";
       $( document ).ready(function() 
         {
            $.ajax({
                     url: show_notifications_url,
                     cache: false,
                     success: function(html) 
                      {
                          $("#notification_results").append(html);
                          //Change the content of the DIV in User's profile page where notifications will be displayed
                      } 
                   }); 
         });
} //function show_notifications

function startTimer() 
   {
      //call show_notifications
      show_notifications();
      //then start interval
      setInterval(show_notifications, 30000); //Refresh after 30 seconds
   } //function startTimer()
</script>

//here is the result in json

{"result":[{"id":"7","creation_date_time":"2018:01:16 07:05:46","view_date_time":"2018:01:16 07:05:46","user_id":"3","notification_text":"Hello","is_viewed":"NO\""},{"id":"8","creation_date_time":"2018:01:16 11:58:03","view_date_time":"2018:01:16 11:58:03","user_id":"1","notification_text":"felix khalawa liked your post","is_viewed":"NO"},
uji moto
  • 1
  • 4
  • 3
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – CBroe Jan 17 '18 at 08:35
  • Change `echo json_encode(array("result"=>$result_array));` to `echo json_encode(array("result"=>$result));` – Hannan Jan 17 '18 at 08:36

1 Answers1

0

You should change the $result_array into $result.

Alternatively you could use compact like so:

<?php
echo json_encode(compact('result'));
?>
user2191227
  • 392
  • 3
  • 15