How to call a Php Function from html - php

I am using a PHP scraper by using simple PHP DOM library. I wrote a function which scrapes data that I need. How can I call that function from html page? I need to show that data in my html page. I am using AngularJS framework and I am working with views.
Here is my code.
function Islamabad_data(){
// Array Declaration
var isb_hi_temp = new Array();
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
echo "Islamabad Data<br>";
echo" <br>High temperature <br>";
foreach($fhtml1->find('#feed-tabs .temp') as $element){
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element)
{
if($i<2)
{
echo $element->plaintext;
?>
isb_hi_temp.push('<?php echo $element; ?>');
<?php
$i++;
}
}
echo isb_data;
}

I know this is not an answer but I've simplified your code. It looks like you want to generate a JavaScript array that can be fetched by Angular. Step 1 one is to properly generate the JSON you need. There were a lot of mistakes in your code -- you cannot intermix JavaScript and PHP in the way that you were doing. Usually in PHP we'll generate an array object using PHP then call json_encode to create the JSON object that will be accessed by the client (in this case, you are using Angular as your client).
function Islamabad_data(){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}
Step 2. Use Angular to call your PHP service. Here is an oversimplified example to help you:
function Hello($scope, $http) {
$http.get('/some/where/somefile.php').
success(function(data) {
$scope.islamabadData = data;
});
}
Also you should really be using Accuweather's API instead of doing data scraping.
http://apidev.accuweather.com/developers/

It might help you:
function loadCitiesData($scope, $http) {
$http.get('/some/where/somefile.php?Islamabad=1').
success(function(data) {
$scope.islamabadData = data;
});
$http.get('/some/where/somefile.php?Lahore=1').
success(function(data) {
$scope.LahoreData = data;
});
}
And your somefile.php file:
<?php
if( !empty($_GET['Islamabad']) ){
$fhtml1 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278');
$fhtml1 = str_get_html($fhtml1);
$day6 = file_get_contents('http://www.accuweather.com/en/pk/islamabad/258278/daily-weather-forecast/258278?day=6');
$day6 = str_get_html($day6);
//echo "Islamabad Data<br>";
//echo" <br>High temperature <br>";
$hiTemp = array();
foreach($fhtml1->find('#feed-tabs .temp') as $element){
$hiTemp[] = $element;
}
$i=0;
foreach($day6->find('#feed-tabs .temp')as $element) {
if ($i<2) {
$hiTemp[] = $element;
}
$i++;
}
echo json_encode( $hiTemp );
}elseif( !empty($_GET['Lahore']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}elseif( !empty($_GET['Multan']) ){
// your code, $yourArray = array('something');
// echo json_encode( $yourArray );
}
?>

Related

Putting arrays in a table using PHP

I'm a beginner in PHP and working on an API project which has to get results from a server I connected via API.
I am getting the results, but I would like to have them well arranged in a simple table.
This is what I am getting:
I used the following code:
$api = new SplynxAPI($api_url, $key, $secret);
$locationsApiUrl = "admin/administration/locations";
echo "<pre>";
echo "List locations\n";
$result = $api->api_call_get($locationsApiUrl);
echo "Result: ";
if ($result) {
echo "Ok!\n";
print_r($api->response);
} else {
echo "Fail! Error code: $api->response_code\n";
print_r($api->response);
}
echo "\n-------------------------------------------------\n";
Kindly assist me on this one.
The following code will render your response in a HTML <table>.
$api = new SplynxAPI($api_url, $key, $secret);
$locationsApiUrl = "admin/administration/locations";
$result = $api->api_call_get($locationsApiUrl);
if ($result) {
echo "<table>";
foreach($api->response as $row){
echo sprintf('<tr><td>%s</td><td>%s</td></tr>', $row['id'], $row['name']);
}
echo '</table>';
} else {
echo "Fail! Error code: $api->response_code\n";
print_r($api->response);
}
echo "\n-------------------------------------------------\n";
You are directly getting the response "$api->response" as an array. So simply use a loop and populate it in table as you like.
Ex:
foreach($api->response as $apiData) {
// Your code
}

Hiding php echo output with json and ajax request

I'm having the problem running php script right when the page loads, and the output is then displayed on the page, which I dont actually want to display. I tried to hide echo with.
<div style='display:none>
but, still doesn't work. I have an idea that "Ajax and JSON Encode function()" will help me to solve this issue of 'making ajax request to same page'. But, I real don't know how to create an array to encode html and php variable that are responsible for the results. Help please.
Here's my ajax function to show the output.
function mass()
{
$.ajax({
url: "page.php",
cache: false,
success: function(html){
$("#container").html(html);
}
});
}
Here's my php script that hold the output of the page
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysql_query($query);
if (isset($_REQUEST['AnswerId'])){
$AnswerId = $_REQUEST['AnswerId'];
}
else {
$AnswerId = 0;
}
$i=0;
while ($mytablerow = mysql_fetch_row($result)) {
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
if (! $treeArray) {
return;
}
foreach($treeArray as $item) {
if ($item[1] == $pid) {
?>
<div class="Div" style="margin-left:<?php echo($level*60);?>px">
<div class="CotDiv">
<div class="ser"><?php echo($item[2]) ; ?></div>
<div class="Mse"><?php echo($item[3]) ; ?></div>
<div class="ito"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=40) {
echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0]){?>
<div id="InnerDiv"><?php ShowForm($AnswerId);?</div><?php ?> </div><?php
echo ('<br/>');
tree($treeArray, $level+1, $item[0]);
}
}
}
tree($mytable, 0);
?>
#enance this isn't the exact same code, but the idea is the same. This probably doesn't output correctly because I don't have an example array of the mysql output to test.
Just a few notes, try not to use globals and just pass the variable into the function. For the sake of time, I kept the output of html within this function, but ideally you'll like to output html through another function.
<?php
// example array
$mytable = [
[1,0,3,4,5,6],
[0,2,3,4,5,6]
];
$answer_id = 1;
function tree($answer_id, $items, $level, $pid = 0) {
if (empty($array))
return;
foreach ($items as $item) {
if ($item[1] == $pid) {
echo sprintf('<div class="Div" style="margin-left:%spx">',$level * 60);
echo '<div class="CotDiv">';
echo sprintf('<div class="ser">%s</div>', $item[2]);
}
if ($level <= 40) {
echo sprintf('Reply', $item[0]);
echo sprintf('Delete', $item[0]);
}
echo '</div>';
if ($answer_id == $item[0]) {
echo sprintf('<div id="InnerDiv">%s</div>', 'FORM OUTPUT HERE');
tree($answer_id, $items, $level++, $item[0]);
}
echo '</div>';
}
}
tree($answer_id, $mytable, 0);
exit;
I really hope this helps to get you on the right track.

Assigning a javascript array with PHP/Postgresql query values in a loop

So, I have a postgresql database and I'm querying a particular column's values and assigning each value to a javascript array. Now I have a javascript function which outputs this data on a map. When i test the array manually (Entering the respective array index one by one), it returns the output perfectly alright. But in a loop (When i want to output all at once), i can only see the first element's output. The rest of the array is simply ignored or there's an error. I don't understand where the mistake is. Here's the code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyC0HZ81Ea8Jy8fJ6zm6_uvPp8UhLg5mczo&sensor=true"></script>
<script type="text/javascript" src="GeoJSON.js"></script>
<script type="text/javascript" src="polygon.js"></script>
<script type="text/javascript">
var geojson_Polygon = new Array();
function kaushik()
{
<?php
require("header.php");
$connection = pg_connect($full);
if(!$connection)
{
pg_close($connection);
}
$result = pg_query($connection, "SELECT ogc_fid, ST_AsGeoJSON(wkb_geometry), name FROM features");
if (!$result)
{
exit;
}
$i = 0;
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[1];";
echo "\n";
echo "\n";
$i++;
}
?>
for (var j=0; j<317; j++)
{
showFeature(geojson_Polygon[j]);
}
}
</script>
If what you want to do is build a JS array , then just do:
<script type="text/javascript">
var data = [ <?php
// --- snip
$first = true;
while ($row = pg_fetch_row($result))
{
if ( $first )
{
$first = false;
}else{
echo ',';
}
echo $row[$i]
}
// ---- snip
?> ];
</script>
i think you should do
while ($row = pg_fetch_row($result))
{
echo "\n";
echo "geojson_Polygon[$i] = $row[$i];";
echo "\n";
echo "\n";
$i++;
}
otherwise the value is always the same
Just read the rows into a php array and then assign it as json.
<script>
...
var geojson_Polygon = <?php echo json_encode($all_rows); ?>;
....

Is it possible to return more than one value from jQuery call?

I have this code: messages.php
if (count($row) > 0)
{
foreach ($row as $r)
{
//some code setting variables
if ($opened_once >= 1)
{
}
else
{
echo "<tr>";
echo '<td><a class="red_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'" id= "subject_id" ><span id = "subject">'.$r['subject'].'</span></a></td>';
echo '<td id = "unique_code1">'.$uniqueCode1.'<span class="pink_text" id = "unique_code2">'.$uniqueCode2.'</span><span id = "unique_code3">'.$uniqueCode3.'</span></td>';
echo "</tr>";
}
}
I need to update $r['id'], $r['subject'], $uniqueCode1, $uniqueCode2, $uniqueCode
My jQuery code:
<script>
$(document).ready(function()
{
refresh();
});
function refresh()
{
$.post('getMessageDetails.php', function (json) {
$("#subject").html(json.subject);
$("#subject_id").html(json.subject_id);
$("#unique_code1").html(json.unique_code1);
$("#unique_code2").html(json.unique_code2);
$("#unique_code3").html(json.unique_code3);
});
window.setTimeout(refresh,30000);
}
</script>
Then I have newMessageCnt.php
<?php
<?php
header('Content-Type: application/json; charset=utf-8');
include('header_application.php');
$limit = 15;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$row = $obj_clean->getMessages($_SESSION['user_id'], $from, $limit);
if (count($row) > 0)
{
foreach ($row as $r)
{
$codeLength = strlen($r['unique_code']);
$codeLength = strlen($r['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($r['unique_code'], -2);
$uniqueCode2 = substr($r['unique_code'], -5, 3);
$uniqueCode1 = substr($r['unique_code'], 0, $firstPartLength);
$message_id = $r['id'];
$subject = $obj_clean->getMessageDetails($message_id);
$opened_once = $obj_clean->getOpenedOnce($message_id);
if ($opened_once >= 1)
{
$array['subject'] = $r['subject'];
$array['subject_id'] = $r['id'];
$array['unique_code1'] = $uniqueCode1;
$array['unique_code2'] = $uniqueCode2;
$array['unique_code3'] = $uniqueCode3;
}
}
}
echo json_encode($array);
exit();
?>
?>
I call this .php somewhere else as well where I just want the value of echo $obj_clean->getUnopenedMessagesCount($_SESSION['user_id']);
But from my messages.php I want
echo '<td><a class="blue_link" href="'.ADDRESS.'view_message.php?id='.$r['id'].'">'.$r['subject'].'</a></td>';
echo '<td>'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</td>';
I'm not sure if I'm doing this right, some advice please?
$.post('ajax_call.php', function (json) {
$("#subject").html(json.subject);
$("#unique_code").html(json.unique_code);
});
//ajax_call.php
<?php
$array['subject']='bla-bla';
$array['unique_code']='1231312';
header('Content-Type: application/json; charset=utf-8');
echo json_encode($array);
exit();
Better would be to have your PHP return an object containing the values you want as properties. This can be sent back to the browser using JSON. Your client-side code see this as an object and can extract the properties and populate the HTML. This separates your presentation (VIEW) from your data (MODEL).
EDIT: Exactly as #TROODON has answered.

How to return the data of an iterate function in codeigniter

i wrote some code in codeigniter
index controller using model 'navigation':
$this->load->model('navigation');
$data['template']=$this->navigation->nav_template();
the nav_template() function generate string that will be output in brower:
function nav_template($uplevel=0)
{
$tablename=$this->db->dbprefix("test");
$sql="select * from $tablename where id_parent=$uplevel "
$menu_item=$this->db->query($sql);
foreach($menu_item->result_array() as $row)
{
if($something)
{
if
{
echo 'some str';
}
self::nav_template($uplevel);//call self
}
else
{
echo 'other str';
}
}
echo '</ul>';
}
in view file i am using an <?php echo $template ?>
but as we all known , i am using echo() to output string. i wanted to store the string in some php varialbe that can be used in view file template tag.
and the nav_template() function just called itself using self php keyword.
nowhere to define the var like this:
$template=''; and no where to return the string?
so , can anyone tell me how to return the output string within the nav_template() instead of echo it directly to browser?
ps: the output data is the formatted html code that will generate a treeview with help of some javascript scripts.
function nav_template($uplevel=0)
{
$tablename=$this->db->dbprefix("test");
$sql="select * from $tablename where id_parent=$uplevel "
$menu_item=$this->db->query($sql);
$out = "";
foreach($menu_item->result_array() as $row)
{
if($something)
{
$out .= self::nav_template($uplevel);
}
else
{
$out .= 'other str';
}
}
$out.= '</ul>';
return $out;
}

Categories