0

i have a script (Users.php) that uses JSON_encode to display an array of objects in an HTML table.

as in:

Users.php :

html //empty table

script //fills the table by using json encode to get php array and display the contents in the table

myPhp.php :

gets info from database and creates the array.

my php file is working just fine and so is my script. the only problem is when i use JSON_encode to get the array from php to the script it shows an error : Uncaught SyntaxError: Unexpected token '<' //on line 1 of php code

my Users.php:

 <body >
    <!-- adding user -->
    <form  class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
      <!-- addUsers.php will add users to the database then display Users.php again -->
    </form>
    <!-- display users -->
        <table id="usersTable">
            <!-- table to display user info -->
        </table>
    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
    <script>

        //display all users in table
        var users = <?php echo JSON_encode($rows); ?>
        
        displayUsers(users);
        function displayUsers(users){
            for(i = 0; i<users.length; i++)
            {
               //create table row
               //add user information to the row
            }
        }     
    </script>
    
</body>

my myPhp.php:

    <?php
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
 }
 
 $query = "SELECT * FROM users";
 $result = $sql->query($query);           
 while($row = $result->fetch_object())
 {
     $rows[]=$row;
 }

 // Close connection
 $result->close();
 $sql->close();

?>

what I've tried:

I tried including the php file before using json_encode

<?php include'myPhp.php' ?>
var users = <?php echo json_encode($rows); ?> 

this works when i run Users.php but if i add a user (by submitting the form in this webpage), add user file reads Users.php again after the user is added, users will end up not displaying and i will have the same error: Uncaught SyntaxError: Unexpected token '<' //in line 1 of myPhp.php

is there any other way to use JSON_encode that won't result in this error?

layla l00
  • 33
  • 1
  • 6
  • Ignore the comment above, I think you need to parse your json data using `JSON.parse(users)` because `json_encode` returns a string not actual json object. – Muhammad Jan 04 '21 at 03:53
  • i tried adding JSON_ parse(users) after users= JSON_encode(). i still ended up with the same error. I don't understand if encode returns a string then how does my Users.php work when i include myPhp.php – layla l00 Jan 04 '21 at 04:37

3 Answers3

0

I'm not getting the same error that you are but MyUsers.php does not know about the variable you are trying to use:



    //display all users
    //users array contains names and roles
    var users = <br />
<b>Warning</b>:  Undefined variable $rows in <b>/var/www/html/public/temp/myUsers.php</b> on line <b>17</b><br />
null
        displayUsers(users);
    function displayUsers(users){
        for(i = 0; i<users.length; i++)
        {
            //create table row
            //add user information to the row
        }
    }

There are a few different ways to get $rows in to myUsers.php.

One way that is easier to understand when you are learning is to do everything in one page: get your data at the top and render the HTML in the bottom.

MyUser2.php: I did not set up a database and hard coded the rows. Assuming that your database setup works you can removed the comments and the hard coded users. Note that since you are outputting a valid JSON array you do not have to re-parse it inside the javascript.

It will look like this in the browser:


    //display all users
    //users array contains names and roles
    var users = ["user1","user2","user3"];

        displayUsers(users);
    function displayUsers(users){
        for(i = 0; i<users.length; i++)
        {
            //create table row
            //add user information to the row
            document.write(users[i] + '<br>');
        }
    }

MyUser2.php file listing:

<?php
/*
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
    exit();
}

$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
    $rows[]=$row;
}

// Close connection
$result->close();
$sql->close();
*/
$rows[] = 'user1';
$rows[] = 'user2';
$rows[] = 'user3';

?>
<body >
<!-- adding user -->
<form  class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
    <!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
    <!-- table to display user info -->
</table>
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>

    //display all users
    //users array contains names and roles
    var users = <?php echo JSON_encode($rows); ?>;

        displayUsers(users);
    function displayUsers(users){
        for(i = 0; i<users.length; i++)
        {
            //create table row
            //add user information to the row
            document.write(users[i] + '<br>');
        }
    }
</script>

</body>

This will get you started. A good framework for learning PHP is CodeIgniter. Laravel is a great framework and more popular but it adds a lot of magical stuff that makes regular PHP harder to learn.

Chris Adams
  • 651
  • 6
  • 8
0

In your "Users.php"

you should first include "myPhp.php"

   <?php include'myPhp.php' ?>

and use it like this:

var json = '<?php echo JSON_encode($rows); ?>';
var users = JSON.parse(json);
Jakob Lämmle
  • 326
  • 1
  • 6
  • This is just the same as the previously deleted answer. Unless calling `global $row;` this wouldn't even work. – Martin Zeitler Jan 04 '21 at 05:31
  • I tried it by my own. For me it works like this. I used the plural $rows variable. (My deleted answer before was a question, by mistake for more details, and I changed it to a answer) – Jakob Lämmle Jan 04 '21 at 05:41
0

solved. the table was displaying correctly when i run Users.php but shows that error when adding a user by executing AddUsers.php which contains readfile('Users.php') at the end of it. the problem was actually in readfile(Users.php)in addUsers.php.

readfile does not execute Users.php but only displays elements in it. therefore the JSON_encode never got executed and users weren't known to Users.php.

i solved this problem by changing readfile('Users.php') in addUsers to include 'Users.php';

Users.php code became :

<?php include 'displayUsers.php'; ?>;
        var users = <?php echo JSON_encode($rows); ?>;
        
        displayUsers(users);
        function displayUsers(users){...}
layla l00
  • 33
  • 1
  • 6