Array of Javascript in PHP - javascript

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.

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 } ?>

Calculation in retrieved JSON API data

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

Inserting value in a JavaScript variable from php code

I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?

Send numbers from php to js in separated files

How to send variables from php to js in separated files. Can I make this without ajax or I need ajax for this. If I need ajax how to make with ajax.
test.php
<?php
$a = 5;
$b = 10;
?>
test.js
var sum =<?php echo $a?> + <?php echo $b?>
document.write(sum);
You can get javascript to know about some data you want to transfer from PHP to javascript quite easily.
But you have to make the javascript valid i.e. I think you were missing the ; at the end of your javascript calculation. It gets a bit hard to see the wood for the tree's sometimes, making sure there is a javascript ; and a PHP ;
<?php
$a = 5;
$b = 10;
echo '<script type="text/javascript">';
echo 'var aFromPhp = ' . $a . ';';
echo 'var bFromPhp = ' . $b . ';';
echo 'var sum = aFromPhp + bFromPhp;';
// or your line
echo 'var sum = ' . $a + $b . ';';
echo '</script>';
NOTE: Doing it this way does tend to mess up the Global scope in javascript with lots of variables and it not really recommended, but it works.

Serve Javascript with PHP: Return/Echo URL/URI

EDIT: Missed the echo statement!
EDIT2: Added missing paranthesis!
EDIT3: Found the solution. See below!
What I am trying to achieve is this:
Dynamically create a Javascript-file with PHP
Serve Javascript-file as .js as embeddable Javascript on different URLs
Dynamically add Page Name and Page URL information inside the JS to be used in Javascript
Currently I do the following:
code.php
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
echo $func->getPageURL();
echo $func->getPageName();
?>
*/
var fred;
...
class.functions.php
<?php
class Functions {
function getPageURL() {
$isHTTPS = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on");
$port = (isset($_SERVER["SERVER_PORT"]) && ((!$isHTTPS && $_SERVER["SERVER_PORT"] != "80") || ($isHTTPS && $_SERVER["SERVER_PORT"] != "443")));
$port = ($port) ? ':'.$_SERVER["SERVER_PORT"] : '';
$data = ($isHTTPS ? 'https://' : 'http://').$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
return $data;
}
function getPageName() {
$data = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
return $data;
}
}
Whenever someone triggers my script-embed code I route them to my code.php. Example:
<script src="//servingdomain/dynamic/123.js"></script>
Now, my code.php does a great job, but returns me this:
/*
servingdomain/dynamic/123.js
*/
/*
https://servingdomain/dynamic/123.js
index.php
*/
var fred;
...
Unfortunately my getPageURL und getPageName are not executed properly, but I am failing to understand why.
I am aiming to get this as output:
/*
servingdomain/dynamic/123.js
*/
/*
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
*/
var fred;
...
How should I takle this problem and get this working correctly either by clean code or dirty workaround ... I am aware of window.location.pathname and window.location.href in Javascript, but I need those to be passed in PHP, since I need to reuse this information to generate dynamic code in code.php.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer and running that through
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)
<?php
$func = new Functions;
$purl = $func->getPageURL()."\n";//use ()
$pname = $func->getPageName();
echo $purl;
echo $pname;
?>
The PHP code is executed just fine, but it just doesn't have any result. You need to write out the values to the file:
<?php header("Content-type: application/x-javascript"); ?>
/*
<?php echo $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] ;?>
*/
/*
<?php
$func = new Functions;
$purl = $func->getPageURL;
$pname = $func->getPageName;
printf("%s\n", $purl);
printf("%s\n", $pname);
?>
*/
var fred;
...
This will write the values of those variables to the javascript file.
Note that if you want to use these values in the javascript code, you need to assign them to a javascript variable like this, outside of javascript comments:
printf("var pageName='%s'\n", $pname);
That way, you can use pageName in your javascript.
Solution
Using $_SERVER['HTTP_REFERER'] gives correct referrer
<?php
echo $_SERVER['HTTP_REFERER'];
$func = new Functions;
echo $func->getPageTitle($_SERVER['HTTP_REFERER']);
?>
Running that through this function
class.functions.php
function getPageTitle($url){
$str = file_get_contents($url);
if(strlen($str)>0){
preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
return $title[1];
}
}
Output
https://otherdomain/blog/awesome-article (page-url)
Awesome Article to read (page-name)

Categories