Calculation in retrieved JSON API data - javascript

Here is my code I need how to add a percentage or number to each value in total field I have tried a lot but nothing works.
<?php
$json=file_get_contents("http://www.upliftinghumanity.net/edd-api/sales/?key=75caa8cb60362c89e6ac2b62730cd516&token=6547d40b82cecb81cb7b0ec928554a9e&number=-1");
$data = json_decode($json);
extract(json_decode($json, true));
if (count($data->sales)) {
// Open the table
echo "<table>";
// Cycle through the array
foreach ($data->sales as $idx => $sales)
{
// Output a row
echo "<tr>";
echo "<td>$sales->total</td>";
echo "<td>$sales->total+3 </td>";
echo "<td>$sales->gateway</td>";
echo "<td>$sales->email</td>";
echo "<td>$sales->transaction_id</td>";
echo "</tr>";
}
// Close the table
echo "</table>";
}
?>
result image

You can add it before echoing it out as a string for example $somevar = $sales->data+1; echo "blahh $somevar"; or echo "blahh {$somevar}";
#Ezekiel the problem is solved what you suggest. i was missing some basic stuff . Thanks –

Hi you can't perform php arithmetic operations which its been qouted as a string, you can probably use the "{$sales->data+3}" but it is always advisable to do thr calculation outside the string as this is only a pseudo code "{$sales->data+3}" and may not work even if you include the curly braces

Related

utilize PHP array as HTML selection

What I got.
I got an PHP which performs a user LDAP query and stores the result in an array. Within the PHP I JSON_encode($myArray) the array and pass this to an JavaScript file with print_r($myArray). In JavaScript I fill a HTML selection with the myArray as source.
The PHP results looks like, which is fine:
["Mickey Mouse","Donald Duck","Minnie Mouse"]
Whats the problem?
Usually I would fill a source based selection like this, which works with JSON files but not in this case:
var fillUserSelection
for (var key in myArray) {
fillUserSelection += "<option>" + myArray[key] + "</option>"
}
document.getElementbyId("").innerHTML = fillUserSelection
I expected Mickey Mouse, Donald Duck and Minnie Mouse as options. Instead I receive each char as options. Like [,",M,i,c,k,e,y.. etc.
What I want.
I want only Mickey Mouse, Donald Duck and Minnie Mouse as options. What do I miss?
Try something like this.
var myArray = JSON.parse(<?php echo json_encode($phpArray) ?>);
Now your array will work.
<?php $myarray = array("Mickey Mouse","Donald Duck","Minnie Mouse"); ?>
<?php json_encode($myarray); ?>
<?php for ($i = 0; $i < count($myarray); $i++) {?>
<?php echo "$myarray[$i] <br/>"; ?>
<?php } ?>

Displaying JSON data created using PHP and MySQL

I have a form on an HTML page which posts a user input to a PHP which executes a SQL statement to get information from a database and output it in JSON. Here is my PHP code to get the JSON data:
<?php
header('Content-type:application/json');
$con = mysqli_connect('localhost','root','','dbname');
if(isset($_POST['submit']))
{
$artist = $_POST['artist'];
$select = mysqli_query($con, "SELECT * FROM tblname WHERE artistName = ". $artist);
$rows = array();
while($row = mysqli_fetch_array($select))
{
$rows[] = $row;
}
echo json_encode($rows);
};
?>
When I submit the form on the HTML page, it goes to the PHP page and I get this result:
[{"0":"6","id":"6","1":"OASIS","artistName":"OASIS","2":"SOME MIGHT SAY","songTitle":"SOME MIGHT SAY","3":"1995-05-06","dateNo1":"1995-05-06"}]
(Code and JSON result have been simplified for this question)
Instead of going to this page, I'd like the data to be displayed nicely on the HTML page so that a user does not see this array. I'm not sure how to do this, any help?
Thank you!
If you want the output formatted nicely, why are you encoding in JSON? JSON, although human-readable, isn't intended to be rendered on-screen as an end product.
I'd recommend looping through the $rows array and building a simple HTML table. You could, of course, wrap the data in any markup you like and even add CSS to style it as you see fit. Here's an example to get you started:
echo "<table>";
foreach($rows as $row) {
foreach($row as $key => $value) {
echo "<tr>";
echo "<td>";
echo $key;
echo "</td>";
echo "<td>";
echo $value;
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
If you only want some of the data rendered, you can simply echo those values:
foreach($rows as $row) {
{
echo "Artist:" . $row['artistName'];
echo "<br>";
echo "Song Title:" . $row['songTitle'];
echo "<br>";
echo "Date:" . $row['dateNo1'];
}
There are two ways to solve this problem :
Perform AJAX call from Javascript to PHP Page and parse the success response in to the HTML.
Simply echo the values in PHP Page or add HTML itself in PHP Page as suggested by Tim.

php post form with variable and javascript submit

I have a list of items from a database and I am trying to post to a specific entry in that list using javascript to submit a form. I have no idea why it's not working though. Here is my code...
<?php
...
while loop to get results {
echo "<form action='scheduled.php?id=$row[id]' method='post' id='sche'>";
echo "<td onclick=\"javascript:document.getElementById('sche').submit();\">".$row['firstname'];
echo "</td>";
echo "</form>";
}
?>
The weird part is that it WILL post, but it doesn't pull the right 'id'. It will take the first one on the list and post to that 'id'.
my URL reads "...scheduled.php?id="
Because of the loop, you are defining many different forms with the same id "sche". You need to give each element their own id.
<?php
...
while loop to get results {
echo "<form action='scheduled.php?id=$row[id]' method='post' id='sche_$row[id]'>";
echo "<td onclick=\"javascript:document.getElementById('sche_$row[id]').submit();\">".$row['firstname'];
echo "</td>";
echo "</form>";
}
?>
Notice the new sche_$row[id] for "id"

Array of Javascript in PHP

I was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.

Transform a PHP array to a Javascript array

Basically I used these codes to transform:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('".$url."');";
}
echo "console.log(img_array);";
echo "</script>";
However, errors occur(firefox debug window) :
Error: unterminated string literal
Source File: http://127.0.0.1/CubeCart/index.php?_a=account
Line: 1, Column: 42
Source Code:
var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
but after I checked the souce file of the html page, the script is shown like this:
<script> var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
');img_array.push('http://gtms01.alicdn.com/tps/i1/T1DQtTFsdFXXaCwpjX.png');console.log(img_array);</script>
With which I don't see anything is wrong.
$jsArray = json_encode ($phpArray);
There is a newline in one of the items in your your php array. Use this:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('". htmlentities(trim($url))."');";
}
echo "console.log(img_array);";
echo "</script>";

Categories