I want to populate a table with some data I get from a database using http requests. I get json encoded data with a php script and then I populate the table using jquery echoed from a php script. I doesn't look neat at all and I am wondering how I can do that differently.
I want to have php and js in separate files because at the moment when I view the source of the webpage I have like 3k+ lines as all the javascript code is generated inside a script tag and due to the large amount of data the javascript code gets repeated. The actual data I have to work with will be even bigger than what I use now for testing.
To give you a better idea of what I am doing at the moment I will write some dummy code here:
<?php
require_once ('functions.php');
include 'header.html';
include 'standardTable.html';
$results = file_get_contents("http://url.com");
$decodedResult = json_decode($results, true);
// I have a function that creates and empty table based on how big the data set is
// This function is placed in functions.php
CreateEmptyTable($decodedResults);
// Then I go ahead and populate the table based on some rules
PopulateTable($decodedResults);
function PopulateTable($res)
{
$rowNum = 0;
for ($i=0;$i<count($res);$i++)
{
$rowNum++;
foreach($res as $key => $value)
{
if ($key == "something")
echo '$("tbody tr#row_'.$rowNum.'")
.find("td:nth-child(id_based_on_key)").text("'.$value.'");
';
else if ($key == "something_else")
echo 'some other jquery lines';
}
}
}
include 'footer.html';
So as you can see this doesn't look pretty at all so I'm wondering if I can structure my code in another way. The thing to keep in mind is that I have to pass php values to the javascript code.
I will appreciate if you can help me out with this and please let me know if you need more details as I wrote something short as an example and it may not be clear enough.
Cheers!
.phpfile extensions. Just add<?php Header("Content-type: application/javascript");at the top. (Some people insist onx-javascript). Then I would suggest you create a Class and use your functions as methods, which can be easily and simply called after including the Class at the top of your php files. You can create a View method for your class to display the HTML.