Return array from PHP file and display onto table using javascript

  • 1
  • Question
  • Updated 4 years ago
I have PHP file on server. It queries database and needs to return multiple rows. In my PHP file I store the query result into an array using:
Some inline while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
$push[] = $row;
}

I need to return this array to my javascript file using echo (as it seems to be only way that works) I am using: echo json_encode($push); at the moment. only problem is that this returns it was a string.

I need to use it on my javascript side as an array as I loop through the 2-D array and display it onto my table. I have been just testing the looping through the 2-D array using hardcoded array I created on my javascript side.

My question is and I am not sure if this is a stupid question that I should already know but I have tried everything I could think of. Is there a better way to return the array as an actual array so I can loop through it in my javascript file using:
Some inline
var result = "<table border=0,width=1000px>";

result += "<thead><tr><th>Speciality</th><th>Job Title</th><th>Location</th><th>View</th></thead><tbody>";

for (var i = 0; i < array.length; i++)
{
result += "<tr>";
for (var j = 0; j < array[i].length; j++)
{
if(j < 3)
{
result += "<td>" + array[i][j] + "</td>";
}
else
{
result += "<td>" + array[i][j] + "</td>";
}
}
result += "<td align=center><button>Click</button></td>";
result += "</tr>";
}
result += "</tbody></table>";
document.getElementById("container").innerHTML = result;
Photo of Patrick Cummins

Patrick Cummins

  • 12 Posts
  • 0 Reply Likes

Posted 4 years ago

  • 1
Photo of JesseMonroy650 (Volunteer)

JesseMonroy650 (Volunteer), Champion

  • 3325 Posts
  • 122 Reply Likes
@Patrick
JSON.org is a great resource for JSON tutorials and libraries.

To get the correct type coming back from a server, Google: JSON mime type.

You want to use a header() with php.

You likely want to use application/json

Jesse
Photo of Patrick Cummins

Patrick Cummins

  • 12 Posts
  • 0 Reply Likes
Thank you for your reply, I will look into what you provided
Photo of Олексій Хіміч

Олексій Хіміч

  • 2 Posts
  • 0 Reply Likes
// On server
$a = array('secret_number'=>rand(),'cherry'=>'red');
echo json_encode($a);

// On client
$(function(){
$.ajax({
url:'https://example.com/file_on_server.php',
type: 'get',
success:function(e){
var d = $.parseJSON(e);
$('#some_div').text('Secret number is '+d.secret_number+ ' and color of cherry is'+d.cherry);
}
})
})
Photo of Patrick Cummins

Patrick Cummins

  • 12 Posts
  • 0 Reply Likes
How would this work with 2D array. Would you just have a loop when printing out onto screen?
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
If you already use jQuery, why not code 'getJSON()' and be done with it?