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?
Related
basically what I've been trying to do is with PHP get a integer from MySQL after that is done, using JavaScript get the integer that PHP has and display it on HTML
<?php include('ConnectionCode.php');
$conn = mysqli_connect($svr, $usr, $pwd, $db) or die("Could not connect " . mysql_error());
$sql = "SELECT RetailPrice FROM WebHosting_PricingCOP WHERE id='32402' LIMIT 1";
$result = mysqli_query($conn, $sql);
$price = mysqli_fetch_array($result);
echo json_encode(number_format($price['RetailPrice'],0,".",","));
mysqli_close($conn)
?>
the code above will connect to the Database and get the value 59,347
now I'm trying to move this single value from PHP to Javascript in order to display it on HTML
<script type="text/javascript">
var PriceValue = "<?php echo json_encode($price) ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
I have gone through many discussions and options here and there and still cant figure out to make it work, when i try to run the html it doesn't display anything
I would greatly appreciate your input
Update:
You may also have a problem with using json_encode inside of "" quotes.
var PriceValue = "<?php echo json_encode($price) ?>";
Instead, use:
var PriceValue = <?php echo json_encode($price) ?>;
or
var PriceValue = <?php echo $price ?>; // if $price is not an object
Note:
To debug this, check the generated HTML source to see what JavaScript you are actually generating.
$price needs to be in the same scope when you try to generate JS.
http://phpfiddle.org/main/code/aeav-gb1w
<?php
$price = 2523525;
?>
<script type="text/javascript">
var PriceValue = "<?php echo $price; ?>";
document.write('<h3>'+PriceValue+'</h3>');
</script>
However, it is going to be preferable for you to use your PHP file as an API endpoint instead of mixing your PHP and JavaScript together.
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.
I'm using x-editable http://vitalets.github.io/x-editable/index.html a jquery inplace editor. Currently I have a working code like below:
<?php
$num_rows = 1;
// store the record of the "tblstudent" table into $row
while ($row = mysqli_fetch_array($result)) {
echo "<script type=\"text/javascript\">
$.fn.editable.defaults.mode = \"popup\";
$('#username$num_rows').editable();
</script> "; //assign num to element
// Print out the contents of the entry
echo '<tr>';
echo '<td><a href="#" id="username' . $num_rows . '" data-type="text" data-pk="' . $row['id'] . '" data-url="post.php" data-title="Edit website">';
echo htmlspecialchars($row['website'], ENT_QUOTES, 'UTF-8');
echo '</a></td>';
echo '</tr>';
$num_rows++;
}
?>
Which result in the following:
but as you can see I use $num_rows in assigning element ID and getting the ID with javascript. I prefer not to use loop to assign uniq ID to element or include the javascript in php tag. Is there any elegant solution than this?
Thanks in advance.
Keep the id as username or infact add class='username' instead of id.
<script type="text/javascript">
$.fn.editable.defaults.mode = "popup";
$('.username').click(function(){
$(this).editable();
})
</script>
I'm using this PHP code to write a HTML table, but it takes time to load. I was thinking it would be a good idea to let JavaScript do the job, but the problem is that $width and $height are dynamic and is defined on the server-side. How do I get around that?
echo "<table>";
for ($y = 0; $y < $height; $y++) {
echo "<tr>";
for ($x = 0; $x < $width; $x++) {
echo '<td x="' . $x . ' y="' . $y . ' id="' . $x . '-' . $y . '"></td>'; //coordinates to be used for cropping later
}
echo '</tr>';
}
echo '</table>';
I'm unsure if this is best practice, but you can echo from PHP directly into Javascript. For example:
<script>
var width = <?php echo $width; ?>;
var height = <?php echo $height; ?>;
//now build table here using the Javascript width and height variables
</script>
Put PHP variables in javascript
<script>
var height = <?php echo $height ?>;
</script>
If no paramount forms are intented to exist in your page, you can store them in hidden HTML tags as hidden inputs, like this:
echo ="<form action ='#' name='form'>
<input type='hidden' name='v_height' id='v_height' value='".$height."'>
<input type='hidden' name='v_width' id='v_width' value='".$width."'>
</form>";
And then in Javascript get those variables and iterate with them.
jHeight = parseInt(document.form.v_height.value);
And so with the width.
I'd appreciate some help in getting a simple demo working of the Twitter typeahead.js library as I've struggled with it over the last two days.
I'm using a MAMP development server on my Macbook, and have a (large) MySQL database table that I'd like to query to use with a typeahead field on a Web page.
This is my main HTML file that I'm using. It literally has one field in it.
type-ahead.php
<?php
// HTML5 Header stuff
echo '<!DOCTYPE html>'.PHP_EOL;
echo '<html>'.PHP_EOL;
echo '<head><meta charset="UTF-8">'.PHP_EOL;
echo '<title>Typeahead Example</title>'.PHP_EOL;
// include the two libraries for typeahead to work
echo '<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '</head>'.PHP_EOL;
echo '<body>'.PHP_EOL;
echo '<h2 class="myclass">Typeahead testing</h2>'.PHP_EOL;
echo 'Type in a search: <input type="text" name="user_search">'.PHP_EOL;
echo "<script type='text/javascript'>".PHP_EOL;
echo "$('#user_search').typeahead({".PHP_EOL;
echo " name: 'user_search',".PHP_EOL;
echo " remote: './type-ahead-ajax.php?query=%QUERY',".PHP_EOL;
//echo " minLength: 3,".PHP_EOL;
//echo " limit: 10".PHP_EOL;
echo "});".PHP_EOL;
echo "</script>".PHP_EOL;
echo '</body></html>'.PHP_EOL;
?>
The source of this from the browser looks OK, but I'll paste it here too just in case.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Typeahead Example</title>
<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>
</head>
<body>
Type in a search: <input type="text" name="user_search">
<script type='text/javascript'>
$('#user_search').typeahead({
name: 'user_search',
remote: './type-ahead-ajax.php?query=%QUERY',
});
</script>
</body></html>
I've tested my call back script separately, and it is definitely connecting to the database and pulling back some results. For example if I use '/type-ahead-ajax.php?query=bleach' as a URL, I get all the products containing the word 'bleach'
type-ahead-ajax.php
<?php
// Connect to the database
try {
$dbh = new PDO('mysql:host=localhost; dbname=menu;', 'root', 'root');
$query = '%'.$_GET['query'].'%'; // add % for LIKE query later
//$query = '%milk%'; //debug
echo $query.PHP_EOL;
// do query
$stmt = $dbh->prepare('SELECT title FROM waitrose WHERE title LIKE :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();
// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$results[] = $row;
echo strtolower($row).PHP_EOL; //debug
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// and return to typeahead
return json_encode($results);
?>
Basically, when you type into the input field nothing happens. It's as though either the callback isn't being called, it's returning nothing, or it's not registered properly in the first place.
Any suggestions?
When you do $('#user_search'), you're referring to an element with id user_search. You haven't, however, given your input any id. Add it:
<input type="text" name="user_search" id="user_search">
If that doesn't work, make sure you get the data you assume by accesssing ./type-ahead-ajax.php?query=%QUERY manually with some query, and check for JavaScript errors in your browser console.