Daedalus
Daedalus

Reputation: 4272

Sending PHP array to JavaScript issue

I have an AJAX POST function that runs a PHP file that queries a MySQL database. It uses the "CONCAT" option in MySQL and then adds each row it receives into an array. I need to get that array from PHP to JavaScript, how would I go about doing this?

I've tried looking it up but nothing that I found either I didn't understand how to actually implement it, or it just flat out didn't work.

$sql_query = substr($sql, 0, -3);

$result = $connection->query($sql_query);

if (!$result) {
    die("Invalid Query: " . mysqli_error());
}

$rowCount = mysqli_num_rows($result);

echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";

$bans = [];

while ($row = $result->fetch_row()) {
    for ($x = 0; $x < $rowCount; $x++) {
        array_push($bans, $row[$x]);
    }
}

I included that part of my PHP code if you need it.

I tried this:

echo(json_encode($bans));

.

      success: function(data) {
          document.getElementById('outputtext').innerHTML = '';
          var array = new Array();
          array = data;
          document.getElementById('outputtext').innerHTML = array;
      }

That returns everything, but adds a lot of "," between them.

Example of an index in the array:

[05-18] Daedalus banned EXAMPLE_USERNAME(EXAMPLE_GUID / EXAMPLE_IP) for EXAMPLE_REASON

I want all the lines from the $bans array to be put into an array in JavaScript.

Upvotes: 0

Views: 63

Answers (2)

Gvidas
Gvidas

Reputation: 1964

This place in your code is wrong:

while ($row = $result->fetch_row()) {
    for ($x = 0; $x < $rowCount; $x++) {
        array_push($bans, $row[$x]);
    }
}

Because you cycle trough records with while and inside once more with for. Use only while:

while ($row = $result->fetch_row()) {
   array_push($bans, $row);
}

Will pull all rows and without nulls.

In your case when you have only single column in your return from database you should use:

while ($row = $result->fetch_row()) {
       array_push($bans, $row[0]);
    }

Upvotes: 0

Akshay Sharma
Akshay Sharma

Reputation: 1112

When you usage echo(json_encode($bans)); that convert php array to json array. To use json in javascript you should first Parse that array like this

success : function(data){
    result      =   JSON.parse(data) ;  
}

Now you check this data console.log(result); Access particular data through key like this

name = result.name;

Upvotes: 1

Related Questions